2008-11-02 80 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])) 

它會自動轉義值禁止符號(如」,「等)