You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

36 lines
1.1 KiB

6 months ago
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