pymsql是Python中操做MySQL的模塊,其使用方法和MySQLdb幾乎相同,可是mysqldb不支持Python3python
pip3 install pymysql
#!/usr/bin/env python # -*- coding:utf-8 -*- import pymysql # 建立鏈接 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123456', db='test',charset='utf8') # 建立遊標 cursor = conn.cursor() # 執行SQL,並返回收影響行數 effect_row = cursor.execute("update hosts set host = '1.1.1.2'") # 執行帶條件SQL,並返回受影響行數 #effect_row = cursor.execute("update hosts set host = '1.1.1.2' where nid > %s", (1,)) # 執行SQL,並返回受影響行數 #effect_row = cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)]) # 提交,否則沒法保存新建或者修改的數據 conn.commit() # 獲取最新自增ID new_id = cursor.lastrowid # 關閉遊標 cursor.close() # 關閉鏈接 conn.close()
#!/usr/bin/env python # -*- coding:utf-8 -*- import pymysql conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1') cursor = conn.cursor() cursor.execute("select * from hosts") # 獲取第一行數據 row_1 = cursor.fetchone() print(row_1) # 獲取前n行數據 # row_2 = cursor.fetchmany(3) # 獲取全部數據 row_3 = cursor.fetchall() cursor.close() conn.close()
關於默認獲取的數據是元祖類型,若是想要或者字典類型的數據,使用設置遊標爲字典類型:mysql
#!/usr/bin/env python # -*- coding:utf-8 -*- import pymysql conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1') # 遊標設置爲字典類型 cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) r = cursor.execute("select * from hosts") result = cursor.fetchone() for k, v in result.items(): print(k,v) cursor.close() conn.close()