要连接到MySQL数据库,首先需要了解以下几个基础概念:
mysql-connector-python
。以下是一个使用Python连接到MySQL数据库的示例代码:
import mysql.connector
# 配置连接参数
config = {
'user': 'your_username',
'password': 'your_password',
'host': '127.0.0.1', # 数据库服务器地址
'database': 'your_database', # 数据库名称
'raise_on_warnings': True
}
try:
# 建立连接
cnx = mysql.connector.connect(**config)
print("成功连接到MySQL数据库")
# 创建游标
cursor = cnx.cursor()
# 执行查询
query = "SELECT * FROM your_table"
cursor.execute(query)
# 获取结果
for row in cursor:
print(row)
except mysql.connector.Error as err:
print(f"连接或查询出错: {err}")
finally:
# 关闭游标和连接
if cursor:
cursor.close()
if cnx:
cnx.close()
通过以上步骤和示例代码,你应该能够成功连接到MySQL数据库。如果遇到具体问题,可以参考相关文档或社区资源进行排查和解决。
领取专属 10元无门槛券
手把手带您无忧上云