5

I'm using mysql.connector and Python 3.7.

For SQL queries, I use this method:

cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3))

The thing is... when I want to print or debug the entire sql query, I can't get the values instead of the %s (I know the whole point is that you can't).

How do you guys do to debug this, then?

Thanks.

6
  • 1
    Doesn't print("INSERT INTO table VALUES (%s, %s, %s)" % (var1, var2, var3)) work? Commented Feb 3, 2020 at 12:26
  • I use string formatting and print it print("INSERT INTO table VALUES ({0}, {1}, {2})".format((var1, var2, var3)) Commented Feb 3, 2020 at 12:30
  • @PaulS I'm gonna look into that. Thank you. Edit: that does work. However how could I get the query that is being sent through the cursor at doing cursor.execute? Commented Feb 3, 2020 at 12:31
  • @Y.S That's the method we were using before this, but heard its insecure? Commented Feb 3, 2020 at 12:32
  • 1
    @andopr if you just print it out to the console, and not passing the formatted string as a sql statement, i'm not sure security is a concern. Commented Feb 3, 2020 at 12:34

2 Answers 2

3

The syntax for printing formatted strings is the following:

name = "John"
print("Hello, %s!" % name)

You can apply that to your SQL statement and print it like this:

print("INSERT INTO table VALUES (%s, %s, %s)" % (var1, var2, var3))
Sign up to request clarification or add additional context in comments.

Comments

0

One thing I would like to add to PaulS' answer is that if any of your variables are strings, you should put the %s associated with that variable inside quotes.

var1 = str()
var2 = int()
var3 = float()

print("INSERT INTO table VALUES ('%s', %s, %s)" % (var1, var2, var3))

Comments

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.