简体   繁体   English

python中的MySQL语法错误,但在MySQL shell中工作

[英]MySQL syntax error in python but working in MySQL shell

I am using MySQLdb in python 我在python中使用MySQLdb

I have a table let table1 with 4 fields one is index which is PRIMARY KEY and suppose others are field2, field3, field4. 我有一个表让table1有4个字段,一个是索引,它是PRIMARY KEY,假设其他是field2,field3,field4。 Since field2 is not unique, I have many rows with same value for this field. 由于field2不是唯一的,因此我有许多行具有相同的值。

Now when I query select field3,field4 from table1 where field2=example, I get a MySQL syntax error near 's'. 现在,当我从table1查询select field3,field4 where field2 = example时,我在's'附近得到一个MySQL语法错误。 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. 为了调试它,我在运行时打印了查询并将其粘贴到MySQL shell中,它返回了与where子句匹配的所有行。

Here is my actual python code 这是我的实际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")

Remove backticks 删除反引号

query = "select field3,field4 from " + atable + " where field2 = %s"
cur.execute(query, (avalue,))
temp = cur.fetchall()

falsetru's solution is almost correct - however there is one little problem with the SQL query: falsetru的解决方案几乎是正确的 - 但SQL查询有一个小问题:

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. 注意where子句的过去部分。 Here you have %s as a string hence the correct way to write the SQL would be: 这里你有%s作为字符串,因此编写SQL的正确方法是:

query = "select field3,field4 from " + atable + " where field2 = '%s'"

Note that %s has been enclosed within single quotes ( ' ) character. 请注意, %s已包含在单引号( ' )字符中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM