Python数据库连接池DBUtils.PooledDB

来源:互联网 发布:软件测试行业如何 编辑:程序博客网 时间:2024/05/22 00:52

1. 未使用连接池连接mysql

import MySQLdbconn = MySQLdb.connect(host = '127.0.0.1', user ='user1', passwd = 'your-password', db ='db1', port = 3306)  cur = conn.cursor()SQL ="select * from t1"r = cur.execute(SQL)r = cur.fetchall()cur.close()conn.close()

2. 使用连接池连接mysql

# -*- coding: utf-8 -*-import MySQLdbfrom DBUtils.PooledDB import PooledDB#5为连接池里的最少连接数pool = PooledDB(MySQLdb, 5, host = '127.0.0.1', user = 'user1', passwd = 'your-password', db = 'db1', port = 3306) #后续每次需要数据库连接用connection()函数获取连接即可。conn = pool.connection()  cur = conn.cursor()SQL = "select * from t1"r = cur.execute(SQL)r = cur.fetchall()cur.close()conn.close()
原创粉丝点击