Thapipo
Thapipo

Reputation: 311

Python MySQL connector select with variable

I've this little query :

id = 'TESTID'
sql = "SELECT ID,PASSWORD FROM USERS WHERE ID = %s"
cursor.execute(sql,(id))

and i'm having the 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 'TESTID''' at line 1

I know this is something about double quotes. I've multiple other query that runs perfectly, but they have like 3 parameters

example :

id = 'TESTID'
GR = 'TEST'
name = 'HELLO'
last_name = 'WORLD'
sql = "INSERT INTO USERS (ID,GR,name,last_name) VALUES (%s,%s,%s,%s)"
cursor.execute(sql,(id,gr,name,last_name))

This one don't have 3 double quote at the beginning and 3 others at the end and runs perfectly so i dont know what to do now.

Thanks you.

Upvotes: 1

Views: 4215

Answers (1)

dopstar
dopstar

Reputation: 1488

One thing you should remember in python is that (7) is the same as 7. For a tuple of length 1, you have to say (7,) (note that important trailing comma).

So change this line: cursor.execute(sql,(id)) to cursor.execute(sql,(id,)).

Upvotes: 4

Related Questions