【问题标题】:Syntax Error when inserting data with variables in MySQLdb Python在 MySQLdb Python 中插入带有变量的数据时出现语法错误
【发布时间】:2013-07-18 21:59:47
【问题描述】:

我正在尝试使用 Python 和 MySQLdb 将一些数据插入 MySQL DB。当我执行以下操作时:

query = "INSERT INTO universitats (universitat) VALUES ('%s')" % (lloc)
cursor.execute(query)
db.commit()

我收到此错误:

Traceback (most recent call last):
  File "read.py", line 39, in <module>
    cursor.execute(query)
  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 'Hospitalet de Llobregat')' at line 1")

我做错了什么?

【问题讨论】:

  • 能否也提供一些query=...前面的代码行,可以帮助解释lloc的价值和universitats的设计

标签: python mysql insert mysql-python


【解决方案1】:

这行:

 query = "INSERT INTO universitats (universitat) VALUES ('%s')" % (lloc)
 cursor.execute(query)

应该是这样的

query = "INSERT INTO universitats (universitat) VALUES (%s)"  
cursor.execute(query,(lloc,))

然后提交。

【讨论】:

    猜你喜欢
    • 2018-01-23
    • 1970-01-01
    • 2019-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    相关资源
    最近更新 更多