一、查询结果是否转为字典'cursorclass': pymysql.cursors.DictCursor
# -*- coding: utf-8 -*-
# TIME: 2020/7/6
import pymysql
from DBUtils.PooledDB import PooledDB
class MysqlPool:
config = {
'creator': pymysql,
'host': 'localhost',
'port': 3306,
'user': 'root',
'password': 'Nice.tv520',
'db': ' spider',
'maxconnections': 7, # 连接池最大连接数量
'cursorclass': pymysql.cursors.DictCursor
}
pool = PooledDB(**config)
def __enter__(self):
self.conn = MysqlPool.pool.connection()
self.cursor = self.conn.cursor()
return self
def __exit__(self, type, value, trace):
self.cursor.close()
self.conn.close()
def db_conn(func):
def wrapper(*args, **kw):
with MysqlPool() as db:
result = func(db, *args, **kw)
return result
return wrapper
@db_conn
def func(db):
db.cursor.execute("""SELECT * FROM user""")
print(db.cursor.fetchall())
# return db.cursor.fetchall()
@db_conn
def func2(db):
db.cursor.execute("""INSERT INTO ` spider`.`user` VALUES (0, 'ming');""")
db.conn.commit()
func()