標籤:
pymysql是Python中操作MySQL的模組,其使用方法和MySQLdb幾乎相同。2.7用MySQLdb,3.0用pymysql。
#下載安裝pip3 install pymysql
使用
執行SQL
#!/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() # 執行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() # 關閉遊標cursor.close()# 關閉串連conn.close()
擷取新建立資料自增ID
#!/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.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])conn.commit()cursor.close()conn.close() # 擷取最新自增IDnew_id = cursor.lastrowid
擷取查詢資料
#!/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() # 擷取前n行資料# row_2 = cursor.fetchmany(3)# 擷取所有資料# row_3 = cursor.fetchall() conn.commit()cursor.close()conn.close()
註:在fetch資料時按照順序進行,可以使用cursor.scroll(num,mode)來移動遊標位置,如:
- cursor.scroll(1,mode=‘relative‘) # 相對當前位置移動
- cursor.scroll(2,mode=‘absolute‘) # 相對絕對位置移動
fetch資料類型
關於預設擷取的資料是元祖類型,如果想要或者字典類型的資料,即:
#!/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("call p1()") result = cursor.fetchone() conn.commit()cursor.close()conn.close()
python---pymysql