Inserting variable values into MySQL database; I'm using (%s) but getting syntax error

Viewed 51

table name: 'tickers_list' (table has only 1 column)

column name: 'Ticker'

The following works:

sql = "INSERT INTO tickers_list (Ticker) VALUES ('AAPL')"
mycursor.execute(sql)
mydb.commit()

But when I try to set it up to accept variables, it's not working:

symbol = 'AAPL'
sql = "INSERT INTO tickers_list (Ticker) VALUES (%s)"
mycursor.execute(sql, symbol)
mydb.commit()

ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s)' at line 1

Where am I going wrong?

2 Answers

You need to execute with a tuple, and a tuple must contain at least one ,. In Python for a single value this means:

mycursor.execute(sql, (symbol,))

Which does look a bit weird, but it's just how it is. For multiple values it looks more normal, no trailing , is necessary.

In addition to what tadman says, strings need quotes:

... ("%s") ...
Related