2014-03-27 41 views
0

我不斷收到同樣的錯誤每次我嘗試將數據插入到一個MySQL表在我的Python腳本:不斷收到錯誤試圖插入到MySQL

[email protected]:~/wikitool-tasks2$ python didyouknow.py 
didyouknow.py:62: Warning: Table 'did_you_know' already exists 
    self.cursor.execute(self.create_query) 
Traceback (most recent call last): 
    File "didyouknow.py", line 121, in <module> 
    test._parse_page() 
    File "didyouknow.py", line 109, in _parse_page 
    self.cursor.execute(record_exists.format(item["name"])) 
    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 MariaDB server version for the right syntax to use near ':Did you know nominations/Cirrus (song)' at line 1") 

該代碼,這是GitHub公開可見的,雖然你會對95到116行特別感興趣。我嘗試了逃避和unicoding字符串,修改我的查詢,什麼都沒有。 (不可否認,我是一名基本的MySQL程序員。)那個地區的任何一位經驗豐富的人能幫我解決這個問題嗎?

+0

發生此錯誤時'item [「name」]'的值是多少? – Joseph

+0

@Joseph item [「name」]是維基百科文章標題。它們有各種形狀和大小,有趣的人物比比皆是。 – ceradon

回答

1

問題是,維基百科標題中的「有趣的字符」正在與SQL語法混淆。你需要處理。這可以通過逃避來完成,但最好的做法是使用SQL參數,就像這樣:

record_exists = u"SELECT COUNT(*) FROM did_you_know WHERE " \ 
       "name = %s" 
# and later on 
self.cursor.execute(record_exists, item["name"]) 

你實際上已經這樣做了以後(線112)。