一、安裝MySQLdb
PyMySQL 是在Python3.x 版本中用于連接 MySQL 服務器的一個庫
① 可以直接pip安裝:pip install PyMySQL
② Git下載地址:PyMySQL
解壓下載文件,不用打開python交互界面,CMD到解壓文件所在目錄
運行 python setup.py install
二、連接MySQL數據庫
#導入pymysql的包
import pymysql
try:
#獲取一個數據庫連接,注意如果是UTF-8類型的,需要制定數據庫
conn=pymysql.connect(host='服務器地址',port=端口號,user='用戶名',passwd='密碼',db='數據庫名稱',charset='連接編碼')
# 使用cursor()方法創建一個游標對象
cur = conn.cursor()
# 使用execute()方法執行SQL查詢
cur.execute('SELECT VERSION()')
data = cur.fetchone()
for d in data:
# 注意int類型需要使用str函數轉義
print('database version: %s' % data)
cur.close() # 關閉游標
conn.close() # 釋放數據庫資源
except Exception: print("發生異常")
運行上面代碼,顯示:database version: 5.7.26,表示連接成功
三、參數說明
pymysql.Connect()參數說明
host(str): MySQL服務器地址
port(int): MySQL服務器端口號
user(str): 用戶名
passwd(str): 密碼
db(str): 數據庫名稱
charset(str): 連接編碼
connection對象支持的方法
cursor() 使用該連接創建并返回游標
commit() 提交當前事務
rollback() 回滾當前事務
close() 關閉連接
cursor對象支持的方法
execute(op) 執行一個數據庫的查詢命令
fetchone() 取得結果集的下一行
fetchmany(size) 獲取結果集的下幾行
fetchall() 獲取結果集中的所有行
rowcount() 返回數據條數或影響行數
close() 關閉游標對象
四、例句
1、select操作
import pymysql
# 打開數據庫連接
db = pymysql.connect(host='localhost',port=3106,user='root',passwd='123456',db='test',charset='utf8')
# 使用cursor()方法獲取操作游標
cursor = db.cursor()
# SQL 查詢語句
# sql = "SELECT * FROM tb_verify_code \
# WHERE phone = '%s' "
# sql查詢數據庫時間最新的一條記錄
sql = "SELECT * FROM tb_verify_code \
WHERE phone ='%s' \
ORDER BY id DESC LIMIT 0,1 "
data = ('18573961234',)
cursor.execute(sql % data)
try:
# 執行SQL語句
cursor.execute(sql % data)
# 獲取所有記錄列表
results = cursor.fetchall()
for row in results:
phone = row[1]
code = row[2]
type = row[3]
# 打印結果
print("phone=%s,code=%s,type=%s" % \
(phone,code,type))
except:
print("Error: unable to fetch data")
# 關閉數據庫連接
db.close()
2、insert操作
import pymysql
db= pymysql.connect(host='localhost',port=3106,user='root',passwd='123456',db='test',charset='utf8')
# 使用cursor()方法獲取操作游標
cur = db.cursor()
sql_insert ="""insert into user(id,username,password) values(4,'張三','123456')"""
try:
cur.execute(sql_insert)
#提交
db.commit()
except Exception as e:
#錯誤回滾
db.rollback()
finally:
db.close()
3、update操作
import pymysql
db= pymysql.connect(host='localhost',port=3106,user='root',passwd='123456',db='test',charset='utf8')
# 使用cursor()方法獲取操作游標
cur = db.cursor()
sql_update ="update user set username = '%s' where id = %d"
try:
cur.execute(sql_update % ("xiongda",3)) #像sql語句傳遞參數
#提交
db.commit()
except Exception as e:
#錯誤回滾
db.rollback()
finally:
db.close()
4、delete操作
import pymysql
db= pymysql.connect(host='localhost',port=3106,user='root',passwd='123456',db='test',charset='utf8')
# 使用cursor()方法獲取操作游標
cur = db.cursor()
sql_delete ="delete from user where id = %d"
try:
cur.execute(sql_delete % (3)) #像sql語句傳遞參數
#提交
db.commit()
except Exception as e:
#錯誤回滾
db.rollback()
finally:
db.close()