连接到MySQL数据库可以使用Python的MySQL Connector模块。以下是一个示例代码,展示如何连接到MySQL数据库:
import mysql.connector
# 连接到MySQL数据库
mydb = mysql.connector.connect(
host="localhost", # 数据库主机地址
user="yourusername", # 数据库用户名
passwd="yourpassword", # 数据库密码
database="yourdatabase" # 数据库名称
)
# 执行SQL查询
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM yourtable")
# 获取查询结果
result = mycursor.fetchall()
for row in result:
print(row)
在上面的代码示例中,将localhost
替换为MySQL服务器的主机地址,将yourusername
替换为数据库的用户名,将yourpassword
替换为数据库的密码,将yourdatabase
替换为要连接的数据库的名称,将yourtable
替换为要查询的表的名称。
请确保已经安装了Python的MySQL Connector模块,可以使用以下命令安装模块:
pip install mysql-connector-python
完成上述步骤后,您就可以连接到MySQL数据库并执行SQL查询了。