在python中使用字符串时去掉“or”

2024-04-27 21:21:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我在字符串中有列名,现在用下面的代码更新mysql中的表:

cursor.execute("""update websites SET %s = %s where weblink = %s""",(key,value,x))

给出错误:

^{pr2}$

键,value='博客',2

在光标.执行key是string,sql表列没有string,如何解决这个问题

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')

Tags: keyinpyexecutestringvaluelinemysql
1条回答
网友
1楼 · 发布于 2024-04-27 21:21:57

“固有”替换对数据有效,但对表名无效。在

SET %s = %s中,第一个%s'blog'替换,而它应该是blog甚至是{}。在

你应该这么做

cursor.execute("""update websites SET `%s` = %%s where weblink = %%s""" % key, (value,x))

因为这是两种截然不同的技术。在

更好的可读性将由

^{pr2}$

如果检查key是否包含`字符,则安全性会提高。在

相关问题 更多 >