天天看點

Python 3 —— 使用 PyMySQL 操作 MySQL8

PyMySQL

是一個純

Python

實作的 MySQL 用戶端操作庫,支援事務、存儲過程、批量執行等。

PyMySQL 遵循

資料庫 API v2.0 規範,并包含了 pure-Python MySQL 用戶端庫。

pip install PyMySQL      

建立資料庫連接配接

import pymysql
 
connection = pymysql.connect(host='localhost',
                             port=3306,
                             user='root',
                             password='root',
                             db='demo',
                             charset='utf8')      

代碼執行個體

#!/usr/bin/python3
 
import pymysql
 
conn = pymysql.connect(host='192.168.195.128',
                             port=3306,
                             user='root',
                             password='Aspirin@369',
                             db='Drugbank',
                             charset='utf8')
 
# 擷取遊标
cursor = conn.cursor()
cursor.execute('SELECT VERSION()')
 
data = cursor.fetchone()  # 獲得第一條資料
print('Database version:', data)
 
# 執行查詢 SQL
cursor.execute('SELECT * FROM `drugbank`')
 
# 擷取單條資料
cursor.fetchone()
 
# 擷取前N條資料
cursor.fetchmany(3)
 
#關閉資料庫
cursor.close()
conn.close()      
Python 3 —— 使用 PyMySQL 操作 MySQL8