SQL语句无法在Python CGI

时间:2017-04-22 21:27:51

标签: python sql cgi

我的数据库中有一个未执行的更新语句。据我所知,它在语法上是正确的。我使用this app来验证语法。 except块正在执行,我不明白为什么。

以下是代码:

for res_posts in list_of_response_ids:
temp_str = res_posts[0] # first element of res_posts tuple is string
temp_str += ":" + str(output[0])
try:
    sql = "UPDATE POST SET res_post_id = %s WHERE post_id = %d;" % (str(temp_str), int(res_posts[1]))
    cursor.execute(sql)
except:
    print "uh oh"

如果信息不足,我可以发布更多代码。

编辑:按照雅各布的建议,我使用raise并收到以下错误:

Traceback (most recent call last):
  File "post.cgi", line 93, in <module>
    cursor.execute(sql)
  File "/usr/lib64/python2.6/site-packages/MySQLdb/cursors.py", line 173, in     execute
self.errorhandler(self, exc, value)
  File "/usr/lib64/python2.6/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorclass, errorvalue
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 ':37 WHERE post_id = 8' at line 1")

非常感谢你!

1 个答案:

答案 0 :(得分:1)

根据您的追溯,您对res_post_idpost_id使用的条目类型有问题。目前,您没有传递res_post_id字符串的表示形式,而是传递文字字符串。如果res_post_id是DB Schema中的字符串,我建议使用%r,如下所示:

sql = "UPDATE POST SET res_post_id = %r WHERE post_id = %d;" % (str(temp_str), int(res_posts[1]))

这将正确引用您的res_post_id值以便插入。

所以你的陈述应该改变:

UPDATE POST SET res_post_id = :37 WHERE post_id = 8;

......对此:

UPDATE POST SET res_post_id = ':37' WHERE post_id = 8;