MySQL连接占用指的是在MySQL数据库服务器上,客户端与服务器之间建立的连接被占用,未能及时释放,导致连接数达到上限,影响数据库性能和可用性。
import mysql.connector
from mysql.connector import pooling
try:
# 创建连接池
connection_pool = mysql.connector.pooling.MySQLConnectionPool(pool_name="mypool",
pool_size=5,
host="localhost",
database="mydb",
user="myuser",
password="mypassword")
# 从连接池获取连接
connection = connection_pool.get_connection()
# 执行SQL查询
cursor = connection.cursor()
cursor.execute("SELECT * FROM mytable")
result = cursor.fetchall()
# 关闭连接
cursor.close()
connection.close() # 这里会返回连接到连接池,而不是真正关闭
except mysql.connector.Error as err:
print(f"Error: {err}")
finally:
# 关闭连接池(实际应用中可能不需要手动关闭)
connection_pool.closeall()
领取专属 10元无门槛券
手把手带您无忧上云