云服务器网站连接MySQL数据库是一个常见的应用场景,涉及到多个基础概念和技术要点。以下是对这个问题的详细解答:
以下是一个使用Python的mysql-connector-python
库连接MySQL数据库的简单示例:
import mysql.connector
try:
# 建立连接
connection = mysql.connector.connect(
host="your_mysql_host", # MySQL服务器地址
user="your_username", # 数据库用户名
password="your_password", # 数据库密码
database="your_database" # 要连接的数据库名
)
if connection.is_connected():
print("成功连接到MySQL数据库")
# 创建游标对象
cursor = connection.cursor()
# 执行SQL查询
cursor.execute("SELECT VERSION()")
version = cursor.fetchone()
print(f"数据库版本: {version[0]}")
except mysql.connector.Error as err:
print(f"连接失败: {err}")
finally:
# 关闭连接
if 'connection' in locals() and connection.is_connected():
cursor.close()
connection.close()
print("MySQL连接已关闭")
希望以上内容能够帮助您更好地理解和解决云服务器网站连接MySQL数据库的相关问题。如有其他疑问,请随时提问。
领取专属 10元无门槛券
手把手带您无忧上云