在MySQLdb Python中使用变量插入数据时出现语法错误

时间:2013-07-18 21:59:47

标签: python mysql insert mysql-python

我正在尝试使用Python和MySQLdb将一些数据插入到MySQL数据库中。当我做以下事情时:

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

我做错了什么?

1 个答案:

答案 0 :(得分:1)

这一行:

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

应该是这样的

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

然后提交。