美文网首页
python mysql 自定义序列化类 以及输出最终sql

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

作者: ArtioL | 来源:发表于2021-10-28 12:45 被阅读0次
    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

    相关文章

      网友评论

          本文标题:python mysql 自定义序列化类 以及输出最终sql

          本文链接:https://www.haomeiwen.com/subject/vchvaltx.html