1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| import pymysql from dbutils.pooled_db import PooledDB
pool = PooledDB( creator=pymysql, maxconnections=20, mincached=5, maxcached=10, maxshared=0, blocking=True, maxusage=1000, setsession=[], host='localhost', port=3306, user='your_user', password='your_password', database='your_db', charset='utf8mb4', autocommit=True, auth_plugin='mysql_native_password' )
def get_connection(): """获取数据库连接""" return pool.connection()
def execute_query(sql, params=None): conn = get_connection() try: with conn.cursor() as cursor: cursor.execute(sql, params) return cursor.fetchall() finally: conn.close()
|