代码
import pymysql
class qieDb:
def __init__(self):
localhost = ''
user = 'root'
passwd = ''
port = 3306
database = "" # 测试库
try:
# 使用 cursor() 方法创建一个游标对象 cursor
self.db = pymysql.connect(host=localhost, user=user, password=passwd, database=database, port=port)
self.cursor = self.db.cursor()
except Exception as e:
print("数据库连接异常:", str(e))
return
def search(self,sqls):
# 使用 execute() 方法执行 SQL 查询,查询room信息
self.cursor.execute(sqls)
data = self.cursor.fetchall() # 查询结果(fetchone、fetchall),返回类型为tuple
# 关闭游标\数据库连接
self.cursor.close()
self.db.close()
return data
def commit(self,sql):
try:
self.cursor.execute(sql)
self.db.commit() # 提交事务
except Exception as e:
print("提交事务异常:", str(e))
self.db.rollback() # 事务回滚
# 关闭游标
self.cursor.close()
self.db.close()
if __name__ == '__main__':
sql=""
qieDb().commit(sql)
sql=""
res=search().commit(sql)
print(res)
运行结果
((62, 1650834628546617345), (15, 1650826416942432258))
"""返回查询的所有结果值,元组格式"""