Python MySQL语句返回错误

Python MySQL语句返回错误,python,sql,Python,Sql,嘿,我对这一切都很陌生,所以请原谅我的愚蠢:) 所以我运行程序,这是我得到的错误信息 user@machine:~/$ python reader.py Traceback (most recent call last): File "reader.py", line 17, in ? cursor.execute("INSERT INTO releases (date, cat, name) values (timestring, y[4], y[7]") File "/usr

嘿,我对这一切都很陌生,所以请原谅我的愚蠢:)

所以我运行程序,这是我得到的错误信息

user@machine:~/$ python reader.py
Traceback (most recent call last):
  File "reader.py", line 17, in ?
    cursor.execute("INSERT INTO releases (date, cat, name) values (timestring, y[4], y[7]")
  File "/usr/lib/python2.4/site-packages/MySQLdb/cursors.py", line 163, in execute
    self.errorhandler(self, exc, value)
  File "/usr/lib/python2.4/site-packages/MySQLdb/connections.py", line 35, 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 '[4], y[7]' at line 1")
user@machine:~/$
所以我假设错误显然来自SQL语句

cursor.execute("INSERT INTO releases (date, cat, name) values (timestring, y[4], y[7]")
下面是y[4]和y[7]的示例

YES      Mail.Sent.To.User:user@work.com.11.2.2008:23.17
发生此错误是因为我应该在尝试将这些值插入数据库之前转义它们吗? 还是我完全没有抓住要点

任何帮助都将不胜感激! 提前谢谢

 cursor.execute("INSERT INTO releases (date, cat, name) values (timestring, y[4], y[7]")
应该是

 cursor.execute("INSERT INTO releases (date, cat, name) values (timestring, '%s', '%s')" % (y[4], y[7]))
调试此类内容的最佳方法是将查询放入变量并使用该变量:

query = "INSERT INTO releases (date, cat, name) values (timestring, '%s', '%s')" % (y[4], y[7])
print query
cursor.execute(query)
这份书面声明将使问题变得非常明显


<>如果你要使用列表变量很多,它会变得非常混乱,考虑只使用一次列表并将变量放入字典中。键入的时间要长一点,但是跟踪发生的事情要容易得多。

正如所指出的,您无法将Python变量值复制到查询中,只能将它们的名称复制到查询中,这对MySQL毫无意义

但是,直接字符串连接选项:

cursor.execute("INSERT INTO releases (date, cat, name) VALUES ('%s', '%s', '%s')" % (timestring, y[4], y[7]))
是危险的,不应使用。如果这些字符串包含诸如“或\in”之类的越界字符,那么您就得到了一个SQL注入,这可能会导致安全隐患。也许在您的特定应用程序中永远不会发生这种情况,但这仍然是一种非常糟糕的做法,初学者的SQL教程确实需要停止使用这种做法

使用MySQLdb的解决方案是让DBAPI层为您在SQL中插入和转义参数值,而不是自己尝试%it:

cursor.execute('INSERT INTO releases (date, cat, name) VALUES (%s, %s, %s)', (timestring, y[4], y[7]))
切勿将“直接字符串连接”与SQL一起使用,因为它不安全、更正确:

cursor.execute('INSERT INTO releases (date, cat, name) VALUES (%s, %s, %s)', (timestring, y[4], y[7]))

它会自动转义值中的禁止符号(如“,”等)

您可能还需要在[y4]和[y7]中的字符串周围加引号
cursor.execute('INSERT INTO releases (date, cat, name) VALUES (%s, %s, %s)', (timestring, y[4], y[7]))