我在字符串中有列名,现在用以下代码更新mysql中的表:
cursor.execute("""update websites SET %s = %s where weblink = %s""",(key,value,x))
给出错误:
_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 ''blog' = 1 where weblink = 'http://blogspot.com/'' at line 1")
键,值='博客',2
在cursor.execute键中是字符串,而sql表列是没有字符串的,如何解决这个问题
Traceback (most recent call last):
File "pgrank.py", line 28, in <module>
cursor.execute("""update websites SET %s = %s where weblink = %s""",(key,value,x))
File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 174, in execute
self.errorhandler(self, exc, value)
File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
_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 '\'blog\'' = 1 where weblink = 'http://blogspot.com/' at line 1')
答案 0 :(得分:2)
“固有”替换适用于数据,但不适用于表名。
在SET %s = %s
中,第一个%s
被'blog'
替换为blog
或`blog`
。
你应该做
cursor.execute("""update websites SET `%s` = %%s where weblink = %%s""" % key, (value,x))
因为这是两种不同的技术。
提供更好的可读性
cursor.execute("update websites SET `" + key +
"` = %s where weblink = %s", (value,x))
如果您检查key
是否包含`
字符,则会增加安全性。