pb怎么连mysql数据库
- 虚拟主机
- 2025-12-27
- 3
要通过Python连接MySQL数据库,通常使用第三方库mysqlconnectorpython或PyMySQL,以下是详细步骤和注意事项:
安装必要的库
首先需要安装MySQL连接驱动,推荐使用mysqlconnectorpython(官方驱动)或PyMySQL(纯Python实现),以mysqlconnectorpython为例,通过pip安装:
pip install mysqlconnectorpython
建立数据库连接
使用mysql.connector.connect()方法建立连接,需提供以下参数:
- host:数据库服务器地址(本地为localhost)
- user:数据库用户名
- password:用户密码
- database:要连接的数据库名(可选)
- port:端口号(默认3306)
示例代码:

创建游标对象
游标用于执行SQL语句和获取结果:
cursor = connection.cursor()
执行SQL语句
(1)执行查询语句
使用execute()方法执行SQL,并通过fetchall()或fetchone()获取结果:
cursor.execute("SELECT * FROM users") results = cursor.fetchall() for row in results: print(row)
(2)执行插入/更新/删除语句
需在执行后调用connection.commit()提交事务:

使用参数化查询防止SQL载入
始终使用占位符(%s)和参数化查询,避免直接拼接SQL字符串:
# 错误示例(易受SQL载入) cursor.execute(f"SELECT * FROM users WHERE name = '{user_input}'") # 正确示例 cursor.execute("SELECT * FROM users WHERE name = %s", (user_input,))
处理连接异常
使用tryexcept捕获连接或执行过程中的异常:
try: connection = mysql.connector.connect( host="localhost", user="your_username", password="wrong_password" ) except mysql.connector.Error as err: print(f"连接错误: {err}")
关闭连接
操作完成后需关闭游标和连接:

cursor.close() connection.close()
使用上下文管理器(推荐)
通过with语句自动管理资源,避免忘记关闭连接:
from mysql.connector import Error def connect_to_mysql(): try: with mysql.connector.connect( host="localhost", user="your_username", password="your_password", database="your_database" ) as connection: with connection.cursor() as cursor: cursor.execute("SELECT VERSION()") version = cursor.fetchone() print(f"MyDB版本: {version[0]}") except Error as e: print(f"错误: {e}") connect_to_mysql()
配置连接池(高并发场景)
对于高并发应用,可使用连接池复用连接:
from mysql.connector import pooling connection_pool = pooling.MySQLConnectionPool( pool_name="mypool", pool_size=5, host="localhost", user="your_username", password="your_password", database="your_database" ) # 从池中获取连接 connection = connection_pool.get_connection() cursor = connection.cursor() cursor.execute("SELECT * FROM users") results = cursor.fetchall() connection.close() # 归还连接到池中
常见问题与解决方案
问题1:mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'localhost'
- 原因:MySQL服务未启动或端口错误。
- 解决:检查MySQL服务状态(sudo systemctl status mysql),确认端口是否为3306。
问题2:mysql.connector.errors.ProgrammingError: 1045: Access denied for user 'user'@'localhost'
- 原因:用户名或密码错误,或用户无权限访问数据库。
- 解决:使用mysql u root p登录MySQL,执行GRANT ALL PRIVILEGES ON your_database.* TO 'your_username'@'localhost';授权。
相关问答FAQs
Q1: 如何在Python中连接远程MySQL数据库?
A1:需确保远程服务器允许外部访问(修改my.cnf中的bindaddress=0.0.0.0),并授予用户远程权限(GRANT ALL PRIVILEGES ON *.* TO 'user'@'%'),连接时指定公网IP:
connection = mysql.connector.connect( host="远程服务器IP", user="your_username", password="your_password" )
Q2: 如何处理MySQL连接超时问题?
A2:可通过connection_timeout参数设置超时时间(默认为28800秒),或定期发送心跳语句保持连接:
connection = mysql.connector.connect( host="localhost", connection_timeout=10 # 10秒超时 ) # 心跳语句 cursor.execute("SELECT 1")