Python连接数据库执行多条SQL查询示例
作者:野牛程序员:2023-12-21 13:34:31python阅读 2646
Python连接数据库执行多条SQL查询示例
import pymysql
# 连接数据库
db_host = "database_host"
db_user = "database_user"
db_password = "database_password"
db_name = "database_name"
connection = pymysql.connect(host=db_host, user=db_user, password=db_password, database=db_name)
# 创建游标对象
cursor = connection.cursor()
# 执行多条SQL查询
try:
# 示例1: 查询操作
query1 = "SELECT * FROM table1"
cursor.execute(query1)
result1 = cursor.fetchall()
# 示例2: 另一条查询操作
query2 = "SELECT * FROM table2"
cursor.execute(query2)
result2 = cursor.fetchall()
# 在这里可以继续添加更多的查询操作...
# 提交事务
connection.commit()
except Exception as e:
# 发生异常时回滚事务
connection.rollback()
print(f"Error: {e}")
finally:
# 关闭游标和连接
cursor.close()
connection.close()
# 处理查询结果
# result1 和 result2 中存储了查询结果,可以根据实际需要进行处理野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

