0

我在字符串中有列名,现在在以下代码中更新 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')
4

1 回答 1

2

“固有”替换适用于数据,但不适用于表名。

SET %s = %s中,第一个%s被替换为'blog'while it should beblog甚至`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包含该`字符,则会增加安全性。

于 2013-04-04T08:18:59.583 回答