2

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
  • If your values of tickets are numbers, use %d. Commented May 25, 2021 at 1:06
  • The tickers are strings, such as AAPL, MSFT, and so on. Commented May 25, 2021 at 1:49

2 Answers 2

1

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.

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

1 Comment

thanks! Haven't run into this before b/c I had only inserted multiple values prior to this, so those were tuples w/o my realizing it.
0

In addition to what tadman says, strings need quotes:

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

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.