python使用德鲁伊连接池访问mysql数据库
时间: 2023-05-28 12:05:25 浏览: 232
python-mysql.zip_MYSQL_pymysql_python MySQL_python连接mysql_连接数据库
5星 · 资源好评率100%
使用德鲁伊连接池访问MySQL数据库需要以下步骤:
1. 安装mysql-connector-python和druid库:
```
pip install mysql-connector-python druid
```
2. 创建数据库连接池:
```python
import mysql.connector
from druid import Druid
config = {
'user': 'root',
'password': 'password',
'host': 'localhost',
'database': 'test'
}
pool = Druid(
mysql.connector.connect,
max_connections=10,
**config
)
```
3. 使用连接池获取数据库连接:
```python
conn = pool.get_connection()
cursor = conn.cursor()
# 执行SQL语句
cursor.execute("SELECT * FROM users")
# 获取查询结果
result = cursor.fetchall()
# 关闭数据库连接
cursor.close()
conn.close()
```
完整示例代码:
```python
import mysql.connector
from druid import Druid
config = {
'user': 'root',
'password': 'password',
'host': 'localhost',
'database': 'test'
}
pool = Druid(
mysql.connector.connect,
max_connections=10,
**config
)
conn = pool.get_connection()
cursor = conn.cursor()
# 执行SQL语句
cursor.execute("SELECT * FROM users")
# 获取查询结果
result = cursor.fetchall()
# 关闭数据库连接
cursor.close()
conn.close()
print(result)
```
阅读全文