2

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")

2 Answers 2

4

Remove backticks

query = "select field3,field4 from " + atable + " where field2 = %s"
cur.execute(query, (avalue,))
temp = cur.fetchall()
Sign up to request clarification or add additional context in comments.

5 Comments

Didn't work... but yes the error is changed. Syntax error shifted to last part
@SudhanshuMishra, What are the values of atable, avalue?
This one is working query = "select field3,field4 from " + atable + " where field2 = %s" % avalue
@SudhanshuMishra, "... %s" % avalue is not good idea. It is vulnerable to SQL injection.
@falsetru execute params should be a tuple, not a list. Like this: cur.execute(query, (avalue,))
0

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.

2 Comments

You don't need to enclose the %s with single quotes, MySQLdb takes care of it. @falsetru 's solution is correct.
Thanks for the note - I was looking at it from a pure SQL perspective and did not know about this tiny tidbit. Thank you once again :)

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.