pythonsqlsqlitesyntaxoperationalerror

OperationalError: near "%": syntax error with sqlite3 in Python


I'm using the sqlite3 package in Python and trying to select a single entry from a table called orders. I would like to get the entry where the value for column order_date ends in 18 (it's a varchar column where the actual value of this entry is "10/20/2018").

As per the guidance on similar questions, I've constructed the query as follows:

sql = """SELECT * FROM orders
            WHERE order_date LIKE %s"""

args = ['%' + '18']

c.execute(sql, args)

But I get this back:

---------------------------------------------------------------------------
OperationalError                          Traceback (most recent call last)
<ipython-input-51-e6a345ebe6eb> in <module>
      6 args = ['%' + '18']
      7 
----> 8 c.execute(sql, args)
      9 conn.commit()
     10 

OperationalError: near "%": syntax error

I've tried structuring the query a number of ways, but get the same error every time. According to the other questions I've browsed, this should work. What's going wrong?


Solution

  • You should use ?as a placeholder for a binding variable instead of %s:

    sql = """SELECT * FROM orders
                WHERE order_date LIKE ?"""