【问题标题】:Print cursor.statement with parameters at error mysql connector在错误 mysql 连接器处打印带有参数的 cursor.statement
【发布时间】:2018-02-16 02:30:35
【问题描述】:

在 Python 中,我使用 mysql 连接器进行查询,使用单独的参数,例如:

 cursor.execute("update tableA set a=%s,b=%s,c=%s", [1,2,3])

我知道当查询成功时我可以使用:

print(cursor.statement)

但是如果出现错误,如何获取包含参数的实际查询?

所以我想得到:

"update tableA set a=1,b=2,c=3"

【问题讨论】:

    标签: python mysql mysql-connector


    【解决方案1】:

    您知道查询成功(至少在技术上 - 结果是否是您预期的结果是另一个问题),因为它没有引发任何异常。所以显而易见的答案是:捕获异常并从那里打印你的参数:

    myquery = "..."
    try:
        cursor.execute("myquery", params)
    except MySQLdb.MySQLError as e:
        # using the logging package would be better
        print("query '{}' with params {} failed with {}".format(myquery, params, e))
        # let the error propagate if you don't 
        # know how to / cannot handle it at this point
        raise 
    

    编辑:如果您想获得已执行的确切查询,那么没有什么是 officially specified by the db api specs。对于 MySQLdb,有一个未记录但公开的 Connection.literal(args) 方法,您可以将其与查询和参数一起使用,即:

        sql = myquery % yourdbconnection.literal(params)
        print("query '{}' failed with {}".format(sql, e))
    

    FWIW 这正是构建执行查询的方式(参见MySQLdb.cursor.execute() 的源代码)。现在虽然是公开的(不以_ 为前缀),但它仍然没有记录,因此没有保证它在下一个版本中仍然可以以这种方式工作 - 当然它是特定于实现的,因此它可能无法与任何其他 db-api 连接器一起使用。

    【讨论】:

    • 谢谢,但这不是我的意思,我更新了我的问题。
    猜你喜欢
    • 2019-10-28
    • 2012-04-08
    • 2013-07-12
    • 2012-07-25
    • 2014-11-08
    • 2019-06-28
    • 1970-01-01
    • 2016-10-11
    相关资源
    最近更新 更多