This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
import pymysql
def query_database():
config = {
'host': 'localhost',
'port': 3306,
'user': 'root',
'password': '123321',
'db': 'gushici',
'charset': 'utf8mb4',
}
try:
# 创建连接
connection = pymysql.connect(**config)
print("数据库连接成功")
# 创建游标,用于执行SQL命令
with connection.cursor() as cursor:
# 执行一个查询示例
cursor.execute("SELECT * FROM shici LIMIT 5")
# 获取查询结果
result = cursor.fetchall()
for row in result:
print(row)
# 自动提交事务,对于只读操作这不是必需的,但确保任何更改会生效
connection.commit()
except pymysql.MySQLError as e:
print(f"数据库查询过程中发生错误: {e}")
finally:
# 连接关闭已经在with语句中自动完成,这里不需要额外判断
pass