python mysql 自定义序列化类 以及输出最终sql

2021-10-28  本文已影响0人  ArtioL
import pymysql
from pymysql.converters import encoders


class MyPyCursor(pymysql.cursors.DictCursor):
    def mogrify(self, query, args=None):
        sql = super().mogrify(query, args)
        print("最终的sql:", sql)
        return sql


def dump(val, mapping=None):
    return encoders[str](str(val), mapping)


class MyDump(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __str__(self):
        return f"<MyDump: a-{self.a} b-{self.b}>"


encoders[MyDump] = dump

if __name__ == '__main__':
    conn = pymysql.connect(host=host, port=int(port), user=user,
                           password=passwd, db=db, charset=charset,
                           conv=encoders,
                           )
    with conn.cursor(MyPyCursor) as cursor:
        cursor.execute("select %s as a", [MyDump('"', "'")])
        result = cursor.fetchone()
        print(result)
image.png
上一篇下一篇

猜你喜欢

热点阅读