mysql连接池设计查询结果转为dict

一、查询结果是否转为字典'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()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值