在python中使用字符串时删除'或'

时间:2013-04-04 07:54:22

标签: python mysql mysql-python

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

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是否包含`字符,则会增加安全性。