pymsql是Python中操作MySQL的模塊,使用它可以完成python和mysql之間的交互
# -*- coding:utf-8 -*-
import pymysql
# 創(chuàng)建連接,db為操作的數(shù)據(jù)庫的名稱
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root', db='mydatabase')
# 創(chuàng)建游標,要使用游標來執(zhí)行數(shù)據(jù)庫的增刪改查操作
cursor = conn.cursor()
# 執(zhí)行SQL,使用execute方法,參數(shù)為sql語句,方法為返回的受影響的行數(shù)
effect_row = cursor.execute('update hosts set name = ‘huanfeng’')
#查找數(shù)據(jù)庫中的數(shù)據(jù),返回影響行數(shù)
effect_row = cursor.execute('select * from student')
#輸出查找結(jié)果,第一條
print cursor.fetchone()
#輸出查找結(jié)果,第二條,以此類推
print cursor.fetchone()
#輸出查找結(jié)果,當前光標之后的所有條
print cursor.fetchall()
# 執(zhí)行SQL,并返回受影響行數(shù)參數(shù)有兩個,第一個為sql語句,第二個為對應的那個數(shù)據(jù)
#effect_row = cursor.execute('update hosts set host = '1.1.1.2' where nid > %s', (1,))
# 執(zhí)行SQL,批量添加數(shù)據(jù),以列表方式增加
#effect_row = cursor.executemany('insert into hosts(host,color_id)values(%s,%s)', [('1.1.1.11',1),('1.1.1.11',2)])
# 提交,不然無法保存新建或者修改的數(shù)據(jù)
conn.commit()
# 關閉游標
cursor.close()
# 關閉連接
conn.close()