pymsql是Python中操作MySQL的模塊,其使用方法和MySQLdb幾乎相同。但目前pymysql支持python3.x而后者不支持3.x版本。
適用環(huán)境
python版本 >=2.6或3.3
mysql版本>=4.1
安裝
可以使用pip安裝也可以手動下載安裝。
使用pip安裝,在命令行執(zhí)行如下命令:
pip install PyMySQL
手動安裝,請先下載。下載地址:https://github.com/PyMySQL/PyMySQL/tarball/pymysql-X.X。
其中的X.X是版本(目前可以獲取的最新版本是0.6.6)。
下載后解壓壓縮包。在命令行中進入解壓后的目錄,執(zhí)行如下的指令:
python setup.py install
建議使用pip安裝。
使用示例
連接數(shù)據(jù)庫如下:
1 2 3 4 5 6 7 8 9 10 11 | import pymysql.cursors # Connect to the database connection = pymysql.connect(host = '127.0.0.1' , port = 3306 , user = 'root' , password = 'zhyea.com' , db = 'employees' , charset = 'utf8mb4' , cursorclass = pymysql.cursors.DictCursor) |
也可以使用字典進行連接參數(shù)的管理,我覺得這樣子更優(yōu)雅一些:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | import pymysql.cursors config = { 'host' : '127.0.0.1' , 'port' : 3306 , 'user' : 'root' , 'password' : 'zhyea.com' , 'db' : 'employees' , 'charset' : 'utf8mb4' , 'cursorclass' :pymysql.cursors.DictCursor, } # Connect to the database connection = pymysql.connect( * * config) |
插入數(shù)據(jù):
執(zhí)行sql語句前需要獲取cursor,因為配置默認自動提交,故在執(zhí)行sql語句后需要主動commit,最后不要忘記關(guān)閉連接:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | from datetime import date, datetime, timedelta import pymysql.cursors #連接配置信息 config = { 'host' : '127.0.0.1' , 'port' : 3306 , 'user' : 'root' , 'password' : 'zhyea.com' , 'db' : 'employees' , 'charset' : 'utf8mb4' , 'cursorclass' :pymysql.cursors.DictCursor, } # 創(chuàng)建連接 connection = pymysql.connect( * * config) # 獲取明天的時間 tomorrow = datetime.now().date() + timedelta(days = 1 ) # 執(zhí)行sql語句 try : with connection.cursor() as cursor: # 執(zhí)行sql語句,插入記錄 sql = 'INSERT INTO employees (first_name, last_name, hire_date, gender, birth_date) VALUES (%s, %s, %s, %s, %s)' cursor.execute(sql, ( 'Robin' , 'Zhyea' , tomorrow, 'M' , date( 1989 , 6 , 14 ))); # 沒有設(shè)置默認自動提交,需要主動提交,以保存所執(zhí)行的語句 connection.commit() finally : connection.close(); |
執(zhí)行查詢:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | import datetime import pymysql.cursors #連接配置信息 config = { 'host' : '127.0.0.1' , 'port' : 3306 , 'user' : 'root' , 'password' : 'zhyea.com' , 'db' : 'employees' , 'charset' : 'utf8mb4' , 'cursorclass' :pymysql.cursors.DictCursor, } # 創(chuàng)建連接 connection = pymysql.connect( * * config) # 獲取雇傭日期 hire_start = datetime.date( 1999 , 1 , 1 ) hire_end = datetime.date( 2016 , 12 , 31 ) # 執(zhí)行sql語句 try : with connection.cursor() as cursor: # 執(zhí)行sql語句,進行查詢 sql = 'SELECT first_name, last_name, hire_date FROM employees WHERE hire_date BETWEEN %s AND %s' cursor.execute(sql, (hire_start, hire_end)) # 獲取查詢結(jié)果 result = cursor.fetchone() print (result) # 沒有設(shè)置默認自動提交,需要主動提交,以保存所執(zhí)行的語句 connection.commit() finally : connection.close(); |
這里的查詢支取了一條查詢結(jié)果,查詢結(jié)果以字典的形式返回:
從結(jié)果集中獲取指定數(shù)目的記錄,可以使用fetchmany方法:
result = cursor.fetchmany(2)
不過不建議這樣使用,最好在sql語句中設(shè)置查詢的記錄總數(shù)。
獲取全部結(jié)果集可以使用fetchall方法:
result = cursor.fetchall()
因為只有兩條記錄,所以上面提到的這兩種查詢方式查到的結(jié)果是一樣的:
在django中使用
在django中使用是我找這個的最初目的。目前同時支持python3.4、django1.8的數(shù)據(jù)庫backend并不好找。這個是我目前找到的最好用的。
設(shè)置DATABASES和官方推薦使用的MySQLdb的設(shè)置沒什么區(qū)別:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mytest',
'USER': 'root',
'PASSWORD': 'zhyea.com',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
關(guān)鍵是這里:我們還需要在站點的__init__.py文件中添加如下的內(nèi)容:
import pymysql
pymysql.install_as_MySQLdb()
最后給大家附上pymysql實現(xiàn)增刪改查的代碼,希望大家能夠喜歡
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | #!/usr/bin/python #coding:gbk import pymysql from builtins import int #將MysqlHelper的幾個函數(shù)寫出來 def connDB(): #連接數(shù)據(jù)庫 conn = pymysql.connect(host = "localhost" ,user = "root" ,passwd = "zx69728537" ,db = "student" ); cur = conn.cursor(); return (conn,cur); def exeUpdate(conn,cur,sql): #更新或插入操作 sta = cur.execute(sql); conn.commit(); return (sta); def exeDelete(conn,cur,IDs): #刪除操作 sta = 0 ; for eachID in IDs.split( ' ' ): sta + = cur.execute( "delete from students where Id=%d" % ( int (eachID))); conn.commit(); return (sta); def exeQuery(cur,sql): #查找操作 cur.execute(sql); return (cur); def connClose(conn,cur): #關(guān)閉連接,釋放資源 cur.close(); conn.close(); result = True ; print ( "請選擇以上四個操作:1、修改記錄,2、增加記錄,3、查詢記錄,4、刪除記錄.(按q為退出)" ); conn,cur = connDB(); number = input (); while (result): if (number = = 'q' ): print ( "結(jié)束操作" ); break ; elif ( int (number) = = 1 ): sql = input ( "請輸入更新語句:" ); try : exeUpdate(conn, cur, sql); print ( "更新成功" ); except Exception: print ( "更新失敗" ); raise ; elif ( int (number) = = 2 ): sql = input ( "請輸入新增語句:" ); try : exeUpdate(conn, cur, sql); print ( "新增成功" ); except Exception: print ( "新增失敗" ); raise ; elif ( int (number) = = 3 ): sql = input ( "請輸入查詢語句:" ); try : cur = exeQuery(cur, sql); for item in cur: print ( "Id=" + str (item[ 0 ]) + " name=" + item[ 1 ]); except Exception: print ( "查詢出錯" ); raise ; elif ( int (number) = = 4 ): Ids = input ( "請輸入Id,并用空格隔開" ); try : exeDelete(conn, cur, Ids); print ( "刪除成功" ); except Exception: print ( "刪除失敗" ); raise ; else : print ( "非法輸入,將結(jié)束操作!" ); result = False ; break ; print ( "請選擇以上四個操作:1、修改記錄,2、增加記錄,3、查詢記錄,4、刪除記錄.(按q為退出)" ); number = input ( "請選擇操作" ); |