1

I want to use a select statement with a variable within the where clause. Ive done resarch on this looking at How to use variables in SQL statement in Python? and Inserting Variables MySQL Using Python, Not Working. Ive tried to implement the solutions provided but its not working. Error code

mysql.connector.errors.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 '?' at line 1

Heres the code:

name = input("Write your name")
mycursor.execute("SELECT name FROM workers WHERE symbol=?", name)

What am i doing wrong?

0

4 Answers 4

3

Okay Spike7 this is exactly what is ideal,

mycursor.execute("SELECT name FROM workers WHERE symbol=%s", (name,))  

or

mycursor.execute("SELECT name FROM workers WHERE symbol=?", (name,)) 

The accepted answer at the first link you given explain evertything.

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

3 Comments

Still getting syntax errors, shoudi take away the symbol?
@Spike7 the query you have written mean select all the names from workers table if the value in symbol column matches the value of the name variable
Yeah it was my fault. When i was looking at the questions it said symbol and i thought it was some mysql language. i changed it to name and it worked fine
2

The MySQL libraries use %s as the placeholder.

mycursor.execute("SELECT name FROM workers WHERE symbol=%s", name)

Despite the similarity, this isn't string substitution.

3 Comments

I am afraid this will return a tuple
Thanks but Im getting a syntax error "mysql.connector.errors.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"
This works for me, having datetime instead of name (string). Thx.
2

You could use

mycursor.execute("SELECT name FROM workers WHERE symbol={}".format(name))

This will only work as long as your variable name is not string

Comments

-1
mycursor.execute("SELECT name FROM workers WHERE symbol=%s"% name)  

That's it

7 Comments

I get this error ysql.connector.errors.ProgrammingError: 1054 (42S22): Unknown column 'symbol' in 'where clause'
listen to your error... it suggests there is no such column as symbol.
@Rhys exactly, Spike recheck the columns available
This is not it. Do not recommend this, ever.
@DanielRoseman your explaination will help us understand python better.
|

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.