環境: Win10 x64 + Python 3.7 +?PyMySQL ?1.0.2 + MySQL 8.0.27
1 安裝
pip install pymysql
2 地址
https://pypi.org/project/pymysql/
3.1 數據庫版本查詢 (search_version.py)
import pymysql# 打開數據庫連接
try:db = pymysql.connect(host='localhost', user='root', passwd='123456', port=3306)print('連接成功!')
except:print('something wrong!')# 使用 cursor() 方法創建一個游標對象 cursor
cursor = db.cursor()# 使用 execute() 方法執行 SQL 查詢
cursor.execute("SELECT VERSION()")# 使用 fetchone() 方法獲取單條數據.fetchone只返回一維元組
data = cursor.fetchone()
print(type(data))
print(data)
print("Database version : %s " % data)# 關閉數據庫連接
db.close()'''
連接成功!
<class 'tuple'>
('8.0.27',)
Database version : 8.0.27
'''
3.2 創建表 (create_table.py)
import pymysql# 打開數據庫連接
try:db = pymysql.connect(host='localhost', user='root', passwd='123456', port=3306, db='db_jupiter')print('連接成功!')
except:print('something wrong!')# 使用 cursor() 方法創建一個游標對象 cursor
cursor = db.cursor()# 使用 execute() 方法執行 SQL,如果表存在則刪除
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")# 使用預處理語句創建表
sql = """CREATE TABLE EMPLOYEE (ID INT NOT NULL AUTO_INCREMENT,FIRST_NAME CHAR(20) NOT NULL COMMENT '名字',LAST_NAME CHAR(20),AGE INT COMMENT '年齡', SEX CHAR(1) COMMENT '性別',INCOME FLOAT NOT NULL COMMENT '收入',PRIMARY KEY (ID))"""cursor.execute(sql)
print('建表成功!')# 關閉數據庫連接
db.close()'''
連接成功!
建表成功!
'''
3.3 插入數據 (insert_update_delete_table.py)
import pymysql# 打開數據庫連接
try:db = pymysql.connect(host='localhost', user='root', passwd='123456', port=3306, db='db_jupiter')print('連接成功!')
except:print('something wrong!')# 使用 cursor() 方法創建一個游標對象 cursor
cursor = db.cursor()# SQL 插入語句
# sql = """INSERT INTO EMPLOYEE(FIRST_NAME,LAST_NAME, AGE, SEX, INCOME) VALUES ('Qin', 'DeXu', 20, 'M', 2000)"""
# sql = """INSERT INTO EMPLOYEE(FIRST_NAME,LAST_NAME, AGE, SEX, INCOME) VALUES ('Li', 'Xiaofei', 20, 'F', 3000)"""
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,LAST_NAME, AGE, SEX, INCOME) VALUES ('Wang', 'HanYu', 20, 'M', 5000)"""# SQL 更新語句
# sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % ('M')# SQL 刪除語句
# sql = "DELETE FROM EMPLOYEE WHERE AGE > %d" % (20)try:# 執行sql語句cursor.execute(sql)# 提交到數據庫執行db.commit()print('數據插入成功!')
except:# 如果發生錯誤則回滾db.rollback()print('數據插入錯誤!')# 關閉數據庫連接
db.close()'''
連接成功!
數據插入成功!
'''
3.4 批量插入數據 (insert_table_many.py)
import pymysql# 打開數據庫連接
try:db = pymysql.connect(host='localhost', user='root', passwd='123456', port=3306, db='db_jupiter')print('連接成功!')
except:print('something wrong!')# 使用 cursor() 方法創建一個游標對象 cursor
cursor = db.cursor()# SQL 插入語句
data = [('DongFang', 'YuXiao', 25, 'M', 2000.30),('OuYang', 'HeHe', 22, 'F', 2000),('GongSun', 'Sheng', 23, 'M', 2000)
]stmt = "INSERT INTO EMPLOYEE (FIRST_NAME,LAST_NAME, AGE, SEX, INCOME) VALUES (%s, %s, %s, %s, %s)"try:# 執行sql語句cursor.executemany(stmt, data)# 提交到數據庫執行db.commit()print('數據插入成功!')
except:# 如果發生錯誤則回滾db.rollback()print('數據插入錯誤!')# 關閉數據庫連接
db.close()'''
連接成功!
數據插入成功!
''''''
說明:
占位符 %s 改成 %d ,報錯。
'''
3.5 查詢數據 (search_table.py)
import pymysql# 打開數據庫連接
try:db = pymysql.connect(host='localhost', user='root', passwd='123456', port=3306, db='db_jupiter')print('連接成功!')
except:print('something wrong!')# 使用 cursor() 方法創建一個游標對象 cursor
cursor = db.cursor()# SQL 查詢語句
sql = "SELECT * FROM EMPLOYEE WHERE INCOME >= %s" % (3000)try:# 執行SQL語句cursor.execute(sql)# rowcount: 這是一個只讀屬性,并返回執行execute()方法后影響的行數。row_count = cursor.rowcountprint(type(row_count))print(row_count)# fetchall(): 接收全部的返回結果行, 獲取所有記錄列表 fetchall返回二維元組(元組中含有元組)results = cursor.fetchall()print(type(results))print(results)for row in results:id = row[0]fname = row[1]lname = row[2]age = row[3]sex = row[4]income = row[5]# 打印結果print('數據查詢成功!')print("id=%s, fname=%s, lname=%s, age=%s, sex=%s, income=%s" % (id, fname, lname, age, sex, income))
except:print("Error: unable to fetch data")# 關閉數據庫連接
db.close()'''
連接成功!
<class 'int'>
2
<class 'tuple'>
((2, 'Li', 'Xiaofei', 20, 'F', 3000.0), (3, 'Wang', 'HanYu', 20, 'M', 5000.0))
數據查詢成功!
id=2, fname=Li, lname=Xiaofei, age=20, sex=F, income=3000.0
數據查詢成功!
id=3, fname=Wang, lname=HanYu, age=20, sex=M, income=5000.0
'''
其他情況:
executemany()方法要求傳入的參數是元組嵌套的列表,列表中每個元組代表一組數據,而元組中的每個值則代表一個數據的字段值。
####################################
批量插入1:
data = [
? ('Jane', date(2005, 2, 12)),
? ('Joe', date(2006, 5, 23)),
? ('John', date(2010, 10, 3)),
]stmt = "INSERT INTO employees (first_name, hire_date) VALUES (%s, %s)"
cursor.executemany(stmt, data)INSERT INTO employees (first_name, hire_date)
VALUES ('Jane', '2005-02-12'), ('Joe', '2006-05-23'), ('John', '2010-10-03')
####################################
批量插入2:
# 定義 SQL 語句
insert_sql = "INSERT INTO person VALUES (%s, %s, %s)"# 定義數據
data = [
? ? ('1', '張三', 18),
? ? ('2', '李四', 19),
? ? ('3', '王五', 20)
]
# 批量插入數據
cursor.executemany(insert_sql, data)批量刪除3:
# 定義 SQL 語句
delete_sql = "DELETE FROM ?WHERE id = %s"
# 定義數據
ids = [(1,), (2,), (3,)]
# 批量刪除數據
cursor.executemany(delete_sql, ids)
參考鏈接:
https://zhuanlan.zhihu.com/p/397765212
http://www.xoxxoo.com/index/index/article/id/288
https://blog.csdn.net/m0_48300767/article/details/131063781
https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-executemany.html