本篇對於Python操做MySQL主要使用兩種方式:python
pymsql是Python中操做MySQL的模塊mysql
pip install pymysqlsql
一、執行SQL 框架
import pymysql conn = pymysql.connect(host = "localhost",port=3306,user = 'root',passwd = '123456',db = 'testdb') #鏈接mysql cursor = conn.cursor() #建立遊標,至關於登錄mysql>所在的位置 effect_row = cursor.execute("update Student set name = 'test' where stu_id = {} ".format(11)) #修改 #effect_row = cursor.execute("insert into Student(name,age,register_date) values(%s,%s,%s)",("mysql",1,"2017-11-15")) #添加,這裏注意即便插入數字也用%s,不要用%d # effect_row = cursor.execute("delete from Student where stu_id > %s",(12,)) #刪除 # effect_row = cursor.executemany("insert into Student(name,age,register_date) values(%s,%s,%s)",(("pymysql",11,"2017-11-15"),('pyorcale',22,"2017-11-15"))) # 插入多條 ##這裏注意effect_row返回的都是收影響的行數 # print(effect_row) conn.commit() #提交,否則沒法保存修改的數據 cursor.close() #關閉遊標 conn.close() #關閉鏈接二、
二、獲取自增idfetch
import pymysql conn = pymysql.connect(host = "localhost",port=3306,user = 'root',passwd = '123456',db = 'testdb') #鏈接mysql cursor = conn.cursor() #建立遊標,至關於登錄mysql>所在的位置 effect_row = cursor.execute("insert into Student(name,age,register_date) values(%s,%s,%s)",("mysql",1,"2017-11-15")) #添加 new_id = cursor.lastrowid #搭配insert語句用,返回最後一次添加記錄的自增id print(new_id) conn.commit() #提交,否則沒法保存修改的數據 cursor.close() #關閉遊標 conn.close() #關閉鏈接
三、獲取查詢數據orm
import pymysql conn = pymysql.connect(host = "localhost",port=3306,user = 'root',passwd = '123456',db = 'testdb') #鏈接mysql # cursor = conn.cursor() #建立遊標,至關於登錄mysql>所在的位置,查找出來的記錄爲列表形式 cursor = conn.cursor(cursor = pymysql.cursors.DictCursor) #如須要設置查找出來的記錄爲字典形式,遊標設置爲字典類型 cursor.execute("select * from Student") #查找語句 # row = cursor.fetchall() #獲取全部記錄 # row = cursor.fetchone() #獲取第一行記錄 cursor.scroll(2,mode='relative') #相對當前位置移動 cursor.scroll(1,mode='absolute') #相對絕對位置移動 row = cursor.fetchmany(3) #獲取前3行記錄 print(row) conn.commit() #提交,否則沒法保存修改的數據 cursor.close() #關閉遊標 conn.close() #關閉鏈接