在Python中连接到数据库可以使用不同的模块或工具。下面是两种常见的方法来连接数据库:
import pymysql
# 建立与数据库的连接
conn = pymysql.connect(host='localhost', port=3306, user='root', password='password', database='mydatabase')
cursor = conn.cursor()
# 执行查询语句
sql = "SELECT * FROM mytable"
cursor.execute(sql)
result = cursor.fetchall()
print(result)
# 关闭连接
cursor.close()
conn.close()
powered by kaifamiao