我正在使用python中的MySQLdb
我有一个表,让索引有4个字段,其中一个是table1,它是主键,假设其他字段是field2,field3,field4。因为field2不是唯一的,所以这个字段有很多行的值都是相同的。
现在,当我查询select field3,field4 from table1 where field2=example时,我在's‘附近得到一个MySQL语法错误。此“%s”属于“select”。
为了调试它,我在运行时打印了查询,并将其粘贴到MySQL shell中,在那里它返回与where子句匹配的所有行。
下面是我实际的python代码
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")发布于 2013-07-21 20:18:05
去掉反引号
query = "select field3,field4 from " + atable + " where field2 = %s"
cur.execute(query, (avalue,))
temp = cur.fetchall()发布于 2013-07-21 21:38:17
falsetru的解决方案几乎是正确的-但是SQL查询有一个小问题:
原始查询及相关代码如下所示:
query = "select field3,field4 from " + atable + " where field2 = %s"
cur.execute(query, (avalue,))
temp = cur.fetchall()注意where子句的过去部分。在这里,SQL%s是一个字符串,因此正确的编写方法应该是:
query = "select field3,field4 from " + atable + " where field2 = '%s'"请注意,%s已用单引号(')字符括起来。
https://stackoverflow.com/questions/17772229
复制相似问题