2012-10-24 19 views
4

我想在mysql中使用python和MySQLdb庫添加一個url到文本行,但是當我運行我的代碼時,它說我的sql語法中有一個錯誤。你能告訴我我做錯了什麼嗎?在python中添加url到mysql行

這裏是我的代碼:

import MySQLdb as mdb 
connection = mdb.connect("Localhost", "root", "", "db") 
cursor = connection.cursor() 
url = mdb.escape_string("http://www.google.com") 
cursor.execute("""INSERT INTO index(url) VALUES(%s)""", (url,)) 

以下是錯誤:

Traceback (most recent call last): 
File "C:\Python27\lib\threading.py", line 551, in __bootstrap_inner 
self.run() 
File "E:\prospector\webworker.py", line 77, in run 
cursor.execute("INSERT INTO index(url) VALUES('%s')", (url_t,)) 
File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 202, in execute 
self.errorhandler(self, exc, value) 
File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler 
raise errorclass, errorvalue 
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 'index(url) VALUES('http://www.google.com/')' at line 1") 

回答

3

我能複製你的問題是這樣的:

mysql> create table `index` (url varchar(50)); 
Query OK, 0 rows affected (0.05 sec) 

mysql> insert into index(url) values ('http://www.google.com'); 
ERROR 1064 (42000): 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 'index(url) values ('http://www.google.com')' at line 1 

mysql> insert into `index`(url) values ('http://www.google.com'); 
Query OK, 1 row affected (0.00 sec) 

index是MySQL中的關鍵字。如果你不使用它作爲表名,你的生活會更容易。 但是,如果你真的想,你可以使用它,但你必須引用它:

cursor.execute("""INSERT INTO `index`(url) VALUES(%s)""", (url,)) 

PS:無需調用

url = mdb.escape_string("http://www.google.com") 

MySQLdb的會自動做你當你調用

cursor.execute("""INSERT INTO index(url) VALUES(%s)""", (url,)) 

事實上,自cursor.execute電話mdb.escape_string你,d自己卷板機它可能導致意外的值被插入到數據庫取決於url值:

In [105]: MySQLdb.escape_string("That's all folks") 
Out[105]: "That\\'s all folks" 

In [106]: MySQLdb.escape_string(MySQLdb.escape_string("That's all folks")) 
Out[106]: "That\\\\\\'s all folks" 
+0

噢,我的天哪,我應該早就知道。非常感謝 :) – TimCPogue