1

In Python I use mysql connector to do queries, with seperate parameters like:

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

I know that when a query succeeded I can use:

print(cursor.statement)

but how can I get the actual query including parameters if I get an error?

So I would like to get:

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

1 Answer 1

2

You know that a query succeeded (at least technically - whether the result is what you expected is another problem) because it didn't raise any exception. So the obvious answer is: catch the exception and print your params from there:

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 

EDIT : if you want to get the exact query that was executed, then there's nothing that's officially specified by the db api specs. For MySQLdb, there's an undocumented yet public Connection.literal(args) method that you can use with your query and params, ie:

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

FWIW that's exactly how the executed query is built (cf the source for MySQLdb.cursor.execute()). Now while public (not prefixed with _) it's still undocumented so there's no garanty it will still work that way in the next release - and of course it's implementation specific so it might not work with any other db-api connector.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks but this isn't exactly what I meant, I updated my question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.