
测试角度看,对 Mysql 数据库,有需求的操作,一般只有基本的插入、查询、修改和删除。本篇就探讨如何使用 Python 语言对基本的插入、查询、修改和删除进行操作。
Python 中有三种库可以连接Mysq:mysql.connector、MySQLdb 和 pymysql, 三者的API使用几乎是一样的,这里推荐使用 pymysql 库。
安装 pymysql
pip install pymysql
查询 Mysql 数据
import pymysql
# 定义数据库信息
MYSQL_DATA={
"host": "192.168.1.11",
"user": "user_name",
"password": "user_password",
"database": "database_name"
}
# 创建连接
connection = pymysql.connect(host=MYSQL_DATA['host'], user=MYSQL_DATA['user'],
password=MYSQL_DATA['password'], database=MYSQL_DATA['database'])
# 创建游标
try: # 使用try...except...finally...确保游标和连接都能被关闭
with connection.cursor() as cursor: # 创建游标
# 定义 select 语句
sql = 'select * from jy_task_v2 limit 10;'
# 执行 select 语句
cursor.execute(sql)
# 获取查询结果
results = cursor.fetchall()
# 打印查询结果
for row in results:
print(row)
except Exception as e:
print(e) # 如果发生错误,打印错误信息定位错误
finally:
connection.close() # 最后关闭连接
变更 Mysql 数据
插入(INSERT)、更新(UPDATE)和删除(DELETE)数据库数据,皆属于变更 Mysql 数据。它们的操作逻辑和流程一致,只有 sql 语句的区别。
变更单条数据
import pymysql
# 定义数据库信息
MYSQL_DATA={
"host": "192.168.1.11",
"user": "user_name",
"password": "user_password",
"database": "database_name"
}
# 创建连接
connection = pymysql.connect(host=MYSQL_DATA['host'], user=MYSQL_DATA['user'],
password=MYSQL_DATA['password'], database=MYSQL_DATA['database'])
# 创建游标
try: # 使用try...except...finally...确保游标和连接都能被关闭
with connection.cursor() as cursor: # 创建游标
# 定义SQL语句,插入: 'INSERT INTO' 更新:'UPDATE' 删除:'DELETE'。
sql = 'update jy_task_v2 set verify_result=1 where status=9;'
# execute 适用于之执行单条数据
results = cursor.execute()
# 打印执行条数
print(results)
# 提交到数据库执行
connection.commit()
except Exception as e:
print(e) # 如果发生错误,打印错误信息定位错误
# 如果发生错误则回滚
connection.rollback()
finally:
connection.close() # 最后关闭连接
变更多条数据
import pymysql
# 定义数据库信息
MYSQL_DATA={
"host": "192.168.1.11",
"user": "user_name",
"password": "user_password",
"database": "database_name"
}
# 创建连接
connection = pymysql.connect(host=MYSQL_DATA['host'], user=MYSQL_DATA['user'],
password=MYSQL_DATA['password'], database=MYSQL_DATA['database'])
# 创建游标
try: # 使用try...except...finally...确保游标和连接都能被关闭
with connection.cursor() as cursor: # 创建游标
# 定义SQL语句,插入: 'INSERT INTO' 更新:'UPDATE' 删除:'DELETE'。
sql = ("INSERT INTO jy_task_v2(lsh, status, verify_type, verify_result, manual_re_verify_mark, "
"manual_re_verify_at, manual_re_verify_by, random_re_verify_mark, random_re_verify_at, "
"random_re_verify_by, start_at, resume_at, finish_at, reset_at, reset_count, created_at, updated_at, "
"digest) VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, "
"%s, %s, %s);")
# 插入数据
data_to_insert = [ # 元组中的数据按顺序依次匹配sql语句中的占位符%s
('240923440010N0092581', 9, 1, -1, 1, 0, 0, 0, 0, 0, 1727338025, 0, 1727338125, 0, 0, 1727338025,
1727338125, '267972e97b046f5db28da0c8ed3c80a5'),
('240923440010N0093174', 9, 1, -1, 1, 0, 0, 0, 0, 0, 1727338026, 0, 1727338152, 0, 0, 1727338025,
1727338152, '41a4612ab3ccc0b788cec359bb9dba8f'),
('240923440010N0093227', 9, 1, -1, 1, 0, 0, 0, 0, 0, 1727338026, 0, 1727338139, 0, 0, 1727338025,
1727338139, '41f4bdb0a2bda32e16d99b6bed57185d'),
('240924440010N0093317', 9, 1, -1, 1, 0, 0, 0, 0, 0, 1727338026, 0, 1727338160, 0, 0, 1727338025,
1727338160, '1c5356e790c96d7dc3a3a872b2ff928b'),
('240924440010N0093510', 9, 1, -1, 1, 0, 0, 0, 0, 0, 1727338026, 0, 1727338159, 0, 0, 1727338025,
1727338159, '19ee2059f0b380538b4ac229bd0ca856'),
('240924440010N0093420', 9, 1, -1, 1, 0, 0, 0, 0, 0, 1727338026, 0, 1727338166, 0, 0, 1727338025,
1727338166, '47d49456356ac1ee2f21a59e40d257f4'),
('240924440010N0093597', 9, 1, -1, 1, 0, 0, 0, 0, 0, 1727338025, 0, 1727338139, 0, 0, 1727338025,
1727338139, 'bee1671c5413f0973eb6a999d691d001'),
('240924440010N0093382', 9, 1, 1, 0, 0, 0, 0, 0, 0, 1727338026, 0, 1727338140, 0, 0, 1727338025,
1727338140, 'f2d1e8d8b42f27620543551cf8c079ef'),
('240923440010N0092497', 9, 1, -1, 1, 0, 0, 0, 0, 0, 1727338026, 0, 1727338141, 0, 0, 1727338025,
1727338141, 'b97937b1932307863694ac59e62fe210'),
('240924440010N0093334', 9, 1, -1, 1, 0, 0, 0, 0, 0, 1727338026, 0, 1727338182, 0, 0, 1727338025,
1727338182, 'e61ec48cd5f23c4d68f7d5fa8872a093')
]
# executemany 适用于之执行多条数据
cursor.executemany(sql, data_to_insert)
# 打印执行条数
print(results)
# 提交到数据库执行
connection.commit()
except Exception as e:
print(e) # 如果发生错误,打印错误信息定位错误
# 如果发生错误则回滚
connection.rollback()
finally:
connection.close() # 最后关闭连接
数据库信息写进文件
在测试项目中,如果有许多地方对数据库进行操作,但数据库环境变了(IP、端口、库名等信息或者想扩展功能),一个个查找变更,显然不美好。万幸,pymysql 库支持读取配置文件数据创建连接,可以在文件里维护数据库环境。
需要在项目里创建一个配置文件(Windows推荐.ini、Linux和MacOS推荐.cof),比如 ‘环境名+应用名.ini’。
连接参数需要写在[client]部分下:
[client]
host = 192.168.1.11
user = user_name
password = user_password
database = database_name
; 端口号不是默认的3306时,可以使用port参数指定端口号
port = 3306
; 字符集(默认utf-8),如果需要指定其他字符集,使用charset参数指定
charset='utf8mb4'
使用 read_default_file 参数读取文件
import pymysql
# 文件的路径可以使用决定路径和相对路径。相对路径,即Mysql.ini与.py在同一目录下。
connection = pymysql.connect(read_default_file='Mysql.ini')
try:
with connection.cursor() as cursor: # 创建游标
# 定义 select 语句
sql = 'select * from jy_task_v2 limit 10;'
cursor.execute(sql)
results = cursor.fetchall()
except Exception as e:
print(e) # 如果发生错误,打印错误信息定位错误
finally:
connection.close() # 最后关闭连接
参数 cursorclass
它用于指定游标的类型,默认为 cursors.Cursor。不同的游标类型会影响查询结果的返回格式和行为:
- cursors.Cursor:默认值,查询结果以元组(Tuple)形式返回,每个字段的值通过索引访问。
- cursors.DictCursor:查询结果以字典(Dict)形式返回,字段名作为键。
- cursors.SSCursor:cursors.Cursor的无缓存模式,不会一次性将全部结果加载到内存中,逐行读取,适用于大数据量场景。
- cursors.SSDictCursor:cursors.DictCursor的无缓存模式,不会一次性将全部结果加载到内存中,逐行读取,适用于大数据量场景。
用法很简单:
import pymysql
from pymysql import cursors
# 创建连接
# cursorclass 的参数值是类对象,不能写进配置文件里,需显性指定
connection = pymysql.connect(read_default_file='Mysql.ini', cursorclass=cursors.DictCursor)
try:
with connection.cursor() as cursor: # 创建游标
# 定义 select 语句
sql = 'select * from jy_task_v2 limit 10;'
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
print(row)
print(row['lsh'])
except Exception as e:
print(e) # 如果发生错误,打印错误信息定位错误
finally:
connection.close() # 最后关闭连接
END

© 转载需要保留原始链接,未经明确许可,禁止商业使用。CC BY-NC-ND 4.0