2

What is the correct way to use .format when I want to pass other variables in the select query for MySQL?

For example I have this query that I can't figure out how to pass all the parameters together correctly

a = "c9" # this is for %s
b = "TEMP" # this is for the first {}
c = "1 hour" # this is for the last {}
c.execute("SELECT Client, {}, Date_Time from data where Client = %s and Date_Time > DATE_SUB(NOW(), INTERVAL {}".format(b,a,c)) # This doesn't work 

I also tried many other variations but they didn't work as well, I am still getting the 1064 error. So, what's the correct way?!

Ahmed Al-haddad
  • 805
  • 2
  • 16
  • 41

2 Answers2

2

In you case,

Try this:

>>> a = "c9" # this is for %s
>>> b = "TEMP" # this is for the first {}
>>> c = "1 hour" # this is for the last {}
>>> sql = "SELECT Client, {}, Date_Time from data where Client = \"{}\" and Date_Time > DATE_SUB(NOW(), INTERVAL {})".format(b,a,c)
>>> sql
'SELECT Client, TEMP, Date_Time from data where Client = "c9" and Date_Time > DATE_SUB(NOW(), INTERVAL 1 hour)'
>>>
>>> cur = db.cursor()
>>> cur.execute(sql)  
>>> data = cur.fetchall()   
>>> cur.close()
SparkAndShine
  • 17,001
  • 22
  • 90
  • 134
1

You want to use a single formatting system - {} is a newer style formatting whereas %s is older.

Change this

c.execute("SELECT Client, {}, Date_Time from data where Client = %s and Date_Time > DATE_SUB(NOW(), INTERVAL {}".format(b,a,c)) # This doesn't work 

to

c.execute("SELECT Client, {}, Date_Time from data where Client = {} and Date_Time > DATE_SUB(NOW(), INTERVAL {}".format(b,a,c))

You can also used named fields:

c.execute("SELECT Client, {field}, Date_Time from data where Client = {client} and Date_Time > DATE_SUB(NOW(), INTERVAL {interval}".format(
    field = b, client = a, interval = c))

However, it's not always the best idea to use string interpolation (i.e formatting) in queries, because of SQL injection attacks and other exploits that can occur. You need to sanitize the user data before passing it into the query – libraries conforming to the DB API should do this for you. See this answer for a more concrete example.

Community
  • 1
  • 1
Rushy Panchal
  • 16,979
  • 16
  • 61
  • 94
  • Thank you sir. I tried your answer first but I had error 1054: `Unknown column 'c9' in 'where clause'`. The other one worked for me. – Ahmed Al-haddad May 01 '16 at 19:35