2008-11-02 213 views
2

哎,我很新的这一切,所以请原谅的愚蠢:)Python的MySQL的语句,返回错误

import os 
import MySQLdb 
import time 

db = MySQLdb.connect(host="localhost", user="root", passwd="********", db="workspace") 
cursor = db.cursor() 

tailoutputfile = os.popen('tail -f syslog.log') 
while 1: 
     x = tailoutputfile.readline() 
     if len(x)==0: 
       break 
     y = x.split() 
     if y[2] == 'BAD': 
       timestring = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) 
       cursor.execute("INSERT INTO releases (date, cat, name) values (timestring, y[4], y[7]") 
     if y[2] == 'GOOD': 
       print y[4] + '\t' + y[7] 

,所以我运行的程序,这是我得到

[email protected]:~/$ 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") 
[email protected]:~/$ 
错误信息

所以我假定错误显然是从SQL语句

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

来这里是什么ÿ一个例子[4]和y [7]看起来像。

YES  Mail.Sent.To.User:[email protected]:23.17 

发生此错误是因为在尝试将它们插入数据库之前,我应该转义这些值吗? 还是我完全错过了点?

任何帮助,将不胜感激! 在此先感谢。

回答

9

正如所指出的那样,您无法将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的你,而不是试图%它自己的护理解决方案:

cursor.execute('INSERT INTO releases (date, cat, name) VALUES (%s, %s, %s)', (timestring, y[4], y[7])) 
4
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) 

打印语句将使它非常明显是什么问题。

如果您打算使用像这样的列表变量,它可能会变得非常混乱,请考虑只使用列表一次并将变量放入字典中。打字时间稍长一些,但更容易跟踪正在发生的事情。

+0

你可能也NE编辑在[y4]和[y7] – Simon 2008-11-02 23:34:55

1

从不使用“直接字符串拼接”与SQL,因为它不是安全,更正确的变体:

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

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