SoftTesting/作业2.py
2025-04-14 23:37:02 +08:00

66 lines
2.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import pymysql
# 定义 数据库工具类
class DBTools(object):
# 创建连接 - 类方法。可以直接使用类名调用!
@classmethod
def __create_conn(cls):
conn = pymysql.connect(host="172.16.28.4", port=3306, user="root", password="root", database="books", charset="utf8")
# 不能遗漏
return conn
# 查一条记录 - 封装为类方法,方便调用
@classmethod
def query_one(cls, sql):
my_conn = None
my_cursor = None
res = None
try:
# 创建连接, 借助类名,调用 类方法 create_conn
my_conn = DBTools.__create_conn()
# 创建游标
my_cursor = my_conn.cursor()
# 执行 sql 语句,做查询
my_cursor.execute(sql)
# 提取一条记录
res = my_cursor.fetchone()
except Exception as err:
print("执行查询SQL失败", str(err))
finally:
# 关闭游标
my_cursor.close()
# 关闭连接
my_conn.close()
# 返回查询结果
return res
# 增删改记录
@classmethod
def db_uid(cls, sql):
my_conn = None
my_cursor = None
try:
# 创建连接
my_conn = DBTools.__create_conn()
# 创建游标
my_cursor = my_conn.cursor()
# 执行 增删改 语句
my_cursor.execute(sql)
print("Affected rows:", my_conn.affected_rows())
# 提交事务
my_conn.commit()
except Exception as err:
print("执行 增删改 SQL 失败:", str(err))
# 回滚事务
my_conn.rollback()
finally:
# 关闭游标
my_cursor.close()
# 关闭连接
my_conn.close()
if __name__ == '__main__':
result = DBTools.query_one("select * from t_hero;")
print("查询语句的结果:", result)
DBTools.db_uid("update t_book set `read` = 100 where id = 3;")