要连接MySQL数据库服务器,您需要了解以下几个基础概念:
以下是一个使用Python的mysql-connector-python
库连接MySQL数据库的示例:
import mysql.connector
# 连接参数
config = {
'user': 'your_username',
'password': 'your_password',
'host': 'your_host', # 例如 'localhost' 或 '192.168.1.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)
# 关闭连接
cursor.close()
cnx.close()
except mysql.connector.Error as err:
print(f"连接失败: {err}")
通过以上步骤和示例代码,您应该能够成功连接到MySQL数据库服务器。如果遇到具体问题,请根据错误信息进行排查。
领取专属 10元无门槛券
手把手带您无忧上云