Python數(shù)據(jù)庫編程之pymysql詳解
Python數(shù)據(jù)庫編程之pymysql
學(xué)習(xí)之前務(wù)必安裝MySQL并已啟動相關(guān)服務(wù)。
一、pymsql的安裝
在python3的環(huán)境中直接使用以下命令即可:
pip install pymysql #或者 pip3 install pymysql
安裝完畢后可使用以下命令查看:
pip list | grep PyMySQL #注意大小寫
結(jié)果如下:

二、連接數(shù)據(jù)庫
pymysql連接數(shù)據(jù)庫使用的是 pymsql.connect() 函數(shù),其常用參數(shù)如下:
| 參數(shù) | 說明 |
|---|---|
| dsn | 數(shù)據(jù)源名稱,給出該參數(shù)表示數(shù)據(jù)庫依賴 |
| host=None | 數(shù)據(jù)庫連接地址 |
| user=None | 數(shù)據(jù)庫用戶名 |
| password=‘’ | 數(shù)據(jù)庫用戶密碼 |
| database=None | 要連接的數(shù)據(jù)庫名稱 |
| port=3306 | 端口號,默認(rèn)為3306 |
| charset=‘’ | 要連接的數(shù)據(jù)庫的字符編碼(可以在終端登陸mysql后使用 \s 查看,如下圖) |
| connect_timeout=10 | 連接數(shù)據(jù)庫的超時時間,默認(rèn)為10 |
| port=3306 | 端口號,默認(rèn)為3306 |

連接完數(shù)據(jù)庫后,需要創(chuàng)建一個游標(biāo)對象,模塊會通過游標(biāo)對象來執(zhí)行sql語句以及獲取查詢結(jié)果,接下來直接通過代碼展示各方法。
示例:
import pymysql
db = pymysql.connect(
host="localhost",
port=3306,
user='root', #在這里輸入用戶名
password='888888', #在這里輸入密碼
charset='utf8mb4'
) #連接數(shù)據(jù)庫
cursor = db.cursor() #創(chuàng)建游標(biāo)對象
sql = 'show databases' #sql語句
cursor.execute(sql) #執(zhí)行sql語句
one = cursor.fetchone() #獲取一條數(shù)據(jù)
print('one:',one)
many = cursor.fetchmany(3) #獲取指定條數(shù)的數(shù)據(jù),不寫默認(rèn)為1
print('many:',many)
all = cursor.fetchall() #獲取全部數(shù)據(jù)
print('all:',all)
cursor.close()
db.close() #關(guān)閉數(shù)據(jù)庫的連接
運(yùn)行結(jié)果:
one: ('coldbox',)
many: (('coldboxtest',), ('db_student',), ('information_schema',))
all: (('mysql',), ('performance_schema',), ('sys',), ('test',), ('wan',))
從結(jié)果可以看出,fetchone(),fetchmany(size),fetchall() 三個函數(shù)返回值都是元組,但是fetchone()返回的是單個元組,另外兩個返回的都是元組的嵌套。
三、創(chuàng)建和管理數(shù)據(jù)庫
使用游標(biāo)對象來執(zhí)行創(chuàng)建和刪除數(shù)據(jù)庫的sql語句示例:
import pymysql
db = pymysql.connect(
host="localhost",
port=3306,
user='root', #在這里輸入用戶名
password='888888', #在這里輸入密碼
charset='utf8mb4'
)
cursor = db.cursor() #創(chuàng)建游標(biāo)對象
try:
sql = 'show databases'
cursor.execute(sql)
print('未創(chuàng)建數(shù)據(jù)庫前:',cursor.fetchall()) #獲取創(chuàng)建數(shù)據(jù)庫前全部數(shù)據(jù)庫
dbname = 'justtest'
sql = 'create database if not exists %s'%(dbname) #創(chuàng)建數(shù)據(jù)庫
cursor.execute(sql)
sql = 'show databases'
cursor.execute(sql)
print('創(chuàng)建新的數(shù)據(jù)庫后:',cursor.fetchall()) #獲取創(chuàng)建數(shù)據(jù)庫后全部數(shù)據(jù)庫
sql = 'drop database if exists %s'%(dbname) #刪除數(shù)據(jù)庫
cursor.execute(sql)
sql = 'show databases'
cursor.execute(sql)
print('刪除新的數(shù)據(jù)庫后:',cursor.fetchall()) #獲取刪除數(shù)據(jù)庫后全部數(shù)據(jù)庫
except Exception as e:
print(e)
db.rollback() #回滾事務(wù)
finally:
cursor.close()
db.close() #關(guān)閉數(shù)據(jù)庫連接
運(yùn)行結(jié)果:
未創(chuàng)建數(shù)據(jù)庫前: (('coldbox',), ('coldboxtest',), ('db_student',), ('information_schema',), ('mysql',), ('performance_schema',), ('sys',), ('test',), ('wan',))
創(chuàng)建新的數(shù)據(jù)庫后: (('coldbox',), ('coldboxtest',), ('db_student',), ('information_schema',), ('justtest',), ('mysql',), ('performance_schema',), ('sys',), ('test',), ('wan',))
刪除新的數(shù)據(jù)庫后: (('coldbox',), ('coldboxtest',), ('db_student',), ('information_schema',), ('mysql',), ('performance_schema',), ('sys',), ('test',), ('wan',))
四、創(chuàng)建和管理表
使用游標(biāo)對象來執(zhí)行創(chuàng)建和管理表的sql語句示例:
import pymysql
db = pymysql.connect(
host="localhost",
port=3306,
user='root', #在這里輸入用戶名
password='888888', #在這里輸入密碼
charset='utf8mb4',
database='justtest' #指定操作的數(shù)據(jù)庫
)
cursor = db.cursor() #創(chuàng)建游標(biāo)對象
try:
tableName = 'user'
sql = 'create table %s (id varchar(20) not null, name varchar(20) not null, primary key(id))'%(tableName)
cursor.execute(sql) #執(zhí)行sql語句,創(chuàng)建表
sql = 'show tables'
cursor.execute(sql)
print('顯示創(chuàng)建的表:',cursor.fetchall()) #顯示創(chuàng)建的表
sql = 'desc %s'%(tableName)
cursor.execute(sql)
print('顯示表結(jié)構(gòu):',cursor.fetchall()) #顯示表結(jié)構(gòu)
except Exception as e:
print(e)
db.rollback() #回滾事務(wù)
finally:
cursor.close()
db.close() #關(guān)閉數(shù)據(jù)庫連接
運(yùn)行結(jié)果:
顯示創(chuàng)建的表: (('user',),)
顯示表結(jié)構(gòu): (('id', 'varchar(20)', 'NO', 'PRI', None, ''), ('name', 'varchar(20)', 'NO', '', None, ''))
總結(jié)
對于修改表結(jié)構(gòu),插入,查詢,刪除數(shù)據(jù)等操作,與上面的操作大體一樣,主要是對 sql 語句的編寫,此處不做贅述。
整體過程:
連接數(shù)據(jù)庫 -> 創(chuàng)建游標(biāo)對象 -> 編寫sql語句 -> 執(zhí)行sql語句 -> 獲取結(jié)果 -> 關(guān)閉數(shù)據(jù)庫連接
connect() 函數(shù)常用參數(shù):
| 參數(shù) | 說明 |
|---|---|
| dsn | 數(shù)據(jù)源名稱,給出該參數(shù)表示數(shù)據(jù)庫依賴 |
| host=None | 數(shù)據(jù)庫連接地址 |
| user=None | 數(shù)據(jù)庫用戶名 |
| password=‘’ | 數(shù)據(jù)庫用戶密碼 |
| database=None | 要連接的數(shù)據(jù)庫名稱 |
| port=3306 | 端口號,默認(rèn)為3306 |
| charset=‘’ | 要連接的數(shù)據(jù)庫的字符編碼(可以在終端登陸mysql后使用 \s 查看,如下圖) |
| connect_timeout=10 | 連接數(shù)據(jù)庫的超時時間,默認(rèn)為10 |
| port=3306 | 端口號,默認(rèn)為3306 |
connect() 函數(shù)返回的連接對象的方法總結(jié):
| 方法名 | 說明 |
|---|---|
| close() | 關(guān)閉數(shù)據(jù)庫的連接 |
| commit() | 提交事務(wù) |
| rollback() | 回滾事務(wù) |
| cursor() | 獲取游標(biāo)對象,操作數(shù)據(jù)庫,如執(zhí)行DML操作,調(diào)用存儲過程等 |
游標(biāo)對象的方法:
| 方法名 | 說明 |
|---|---|
| callproc(procname,[,parameters]) | 調(diào)用存儲過程,需要數(shù)據(jù)庫支持 |
| close() | 關(guān)閉當(dāng)前游標(biāo) |
| execute(operation,[,parameters]) | 執(zhí)行數(shù)據(jù)庫操作,sql語句或者數(shù)據(jù)庫命令 |
| executemany(operation, seq_of_params) | 用于批量操作 |
| fetchone() | 獲取查詢結(jié)果集合中的下一條記錄 |
| fetchmany(size) | 獲取指定數(shù)量的記錄 |
| fetchall() | 獲取查詢結(jié)果集合所有記錄 |
| nextset() | 跳至下一個可用的數(shù)據(jù)集 |
| arraysize | 指定使用fetchmany()獲取的行數(shù),默認(rèn)為1 |
| setinputsizes(size) | 設(shè)置調(diào)用execute*()方法時分配的內(nèi)存區(qū)域大小 |
| setoutputsizes(size) | 設(shè)置列緩沖區(qū)大小,對大數(shù)據(jù)列尤其有用 |
以上就是Python數(shù)據(jù)庫編程之pymysql詳解的詳細(xì)內(nèi)容,更多關(guān)于Python pymysql的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
使用Scrapy框架爬取網(wǎng)頁并保存到Mysql的實(shí)現(xiàn)
Python OpenCV實(shí)現(xiàn)測量圖片物體寬度
Python 解析庫json及jsonpath pickle的實(shí)現(xiàn)

