Reputation: 2094
I am using MySQLdb in python
I have a table let table1 with 4 fields one is index which is PRIMARY KEY and suppose others are field2, field3, field4. Since field2 is not unique, I have many rows with same value for this field.
Now when I query select field3,field4 from table1 where field2=example, I get a MySQL syntax error near 's'. This 's' belongs to 'select'.
To debug it I printed the query in runtime and pasted it in MySQL shell where it returned all the rows matching the where clause.
Here is my actual python code
query = "select `field3`,`field4` from `" + atable + "` where `field2` = '"+avalue+"'"
cur.execute(query)
temp = cur.fetchall()
Error:
_mysql_exceptions.ProgrammingError: (1064, "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")
Upvotes: 2
Views: 7436
Reputation: 4767
falsetru's solution is almost correct - however there is one little problem with the SQL query:
The original query and the related code is as shown below:
query = "select field3,field4 from " + atable + " where field2 = %s"
cur.execute(query, (avalue,))
temp = cur.fetchall()
Note the past part of the where clause. Here you have %s as a string hence the correct way to write the SQL would be:
query = "select field3,field4 from " + atable + " where field2 = '%s'"
Note that %s has been enclosed within single quotes (') character.
Upvotes: 0
Reputation: 368914
Remove backticks
query = "select field3,field4 from " + atable + " where field2 = %s"
cur.execute(query, (avalue,))
temp = cur.fetchall()
Upvotes: 4