標籤:mini exe into ext 模組 print utf8 語句 無法
python3中操作mysql資料需要安裝一個第三方模組,pymysql,使用pip install pymysql安裝即可.
在python2中是MySQLdb模組,在python3中沒有MySQLdb模組了,所以使用pymysql。
import pymysql # 建立串連,指定資料庫的ip地址,帳號、密碼、連接埠號碼、要操作的資料庫、字元集 conn = pymysql.connect(host=‘127.0.0.1‘, port=3306, user=‘root‘, passwd=‘123456‘, db=‘data‘,charset=‘utf8‘) # 建立遊標 cursor = conn.cursor() # 執行SQL,並返回收影響行數 effect_row = cursor.execute("update students set name = ‘niuhy‘ where id = 1;") # 執行SQL,並返回受影響行數 #effect_row = cursor.execute("update students set name = ‘niuhy‘ where id = %s;", (1,)) # 執行SQL,並返回受影響行數 effect_row = cursor.executemany("insert into students (name,age) values (%s,%s); ", [("andashu",18),("12345",20)]) #執行select語句 cursor.execute("select * from students;") #擷取查詢結果的第一條資料,返回的是一個元組 row_1 = cursor.fetchone() # 擷取前n行資料 row_2 = cursor.fetchmany(3) # 擷取所有資料 row_3 = cursor.fetchall() # 提交,不然無法儲存建立或者修改的資料 conn.commit() # 擷取最新自增ID new_id = cursor.lastrowid print(new_id) # 關閉遊標 cursor.close() # 關閉串連 conn.close() 上面的操作,擷取到的返回結果都是元組,如果想擷取到的結果是一個字典類型的話,可以使用下面這樣的操作 import pymysql # 建立串連,指定資料庫的ip地址,帳號、密碼、連接埠號碼、要操作的資料庫、字元集 conn = pymysql.connect(host=‘127.0.0.1‘, port=3306, user=‘root‘, passwd=‘123456‘, db=‘data‘,charset=‘utf8‘) # 建立遊標 cursor = conn.cursor() cursor = coon.cursor(cursor=pymysql.cursors.DictCursor)#需要指定遊標的類型,字典類型 # 執行SQL cursor.execute("select * from user;") #擷取返回結果,這個時候返回結果是一個字典 res = cursor.fetchone()#返回一條資料,如果結果是多條的話 print(res) res2 = cursor.fetchall()#所有的資料一起返回
python操作mysql