Python 连接 MySQL 数据库
warning:
这篇文章距离上次修改已过190天,其中的内容可能已经有所变动。
要在Python中连接MySQL数据库,你可以使用mysql-connector-python
库。首先,确保已经安装了这个库,如果没有安装,可以通过pip安装:
pip install mysql-connector-python
以下是一个简单的示例,展示了如何连接到MySQL数据库并执行一个查询:
import mysql.connector
# 连接到MySQL数据库
config = {
'user': 'your_username',
'password': 'your_password',
'host': 'localhost',
'database': 'your_database'
}
cnx = mysql.connector.connect(**config)
# 创建一个游标对象
cursor = cnx.cursor()
# 执行一个查询
query = ("SELECT * FROM your_table")
cursor.execute(query)
# 获取查询结果
for (column1, column2) in cursor:
print("{}, {}".format(column1, column2))
# 关闭游标和连接
cursor.close()
cnx.close()
请确保替换your_username
, your_password
, localhost
, your_database
, 和your_table
为你的MySQL数据库的实际登录凭据和你想要查询的表名。
评论已关闭