【问题标题】:change paramstyle on python MySQLdb module在 python MySQLdb 模块上更改 paramstyle
【发布时间】:2014-08-11 06:06:55
【问题描述】:

我的默认 mysql 参数是 :'format'

>>>MySQLdb.paramstyle
'format'

我想将默认参数样式更改为“pyformat”,因为我可以查询类似“WHERE name=%(name)s”的内容。 有什么办法吗?

【问题讨论】:

    标签: python mysql


    【解决方案1】:

    我敢肯定,如果不在图书馆内部胡闹,这是不可能的……-paramstylehardcoded 以符合 PEP 249。

    还要注意escaping always uses a tuple ...

    我想你可以如果你更换它:

    if args is not None:
        query = query % tuple(( get_codec(a, self.encoders)(db, a) for a in args ))
    

    类似:

    if args is not None:
        if isinstance(args, tuple):
            args = tuple(get_codec(a, self.encoders)(db, a) for a in args)
        elif isinstance(args, dict):
            args = {k: get_codec(a, self.encoders)(db, a) for a in args}
        query = query % args
    

    您可能希望在 Cursor 子类中执行此操作 - 您可以将其作为参数传递给连接...

    最终,这有点“麻烦”,因为重写整个执行方法可能会迫使您使用一堆不在“公共”API 中的东西,但至少应该是可能的。

    【讨论】:

    • @Mahyar -- 当然有办法。问题是它做起来有多容易,以及您愿意在多大程度上依赖实现细节来做到这一点:-)
    • @Mahyar -- 有趣的是,如果您阅读 docstring,它的行为就像应该支持 %(...) 格式,但查看代码,我很难时间相信它是。 :-)
    猜你喜欢
    • 2016-04-06
    • 2011-03-15
    • 1970-01-01
    • 2012-12-25
    • 2017-07-15
    • 2011-11-17
    • 1970-01-01
    • 1970-01-01
    • 2021-01-28
    相关资源
    最近更新 更多