python-MySQL鏈接
python鏈接MySQL,主要利用庫
pip install mysql-connector-python
import mysql.connector# 配置连接参数
config = {"user": "your_username","password": "your_password","host": "localhost", # 或远程数据库地址"database": "your_database","port": 3306, # 默认端口"charset": "utf8mb4" # 推荐字符集
}try:# 建立连接conn = mysql.connector.connect(**config)cursor = conn.cursor()# 执行 SQL 查询cursor.execute("SELECT VERSION()") # 這裏是執行語句version = cursor.fetchone() print(f"MySQL版本: {version[0]}")except mysql.connector.Error as err:print(f"数据库错误: {err}")
finally:if 'conn' in locals() and conn.is_connected():cursor.close()conn.close()print("数据库连接已关闭")