2015-03-19 69 views
0

我試圖通過編寫管道輸送到數據到MySQL存儲,但它發生:Python的MySQL錯誤#1064

_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 'desc,pic)values ('xe4\xbe\x9b\xe5\xba.......' at line 1")

這裏是我的代碼:

def __init__(self): 
    #self.file = codecs.open('tutorial_data.json','wb',encoding='utf-8') 
    self.dbpool = adbapi.ConnectionPool('MySQLdb', 
             host = 'localhost', 
             port = 3306, 
             db = 'project', 
             user = 'root', 
             passwd = '', 
             cursorclass = MySQLdb.cursors.DictCursor, 
             charset = 'utf8', 
             use_unicode = True) 
def process_item(self, item, spider): 
    query = self.dbpool.runInteraction(self._conditional_insert, item) 
    query.addErrback(self.handle_error) 
    return item 

def _conditional_insert(self,tx,item): 

     tx.execute(
     "INSERT INTO raw (title,area,date,sclass,desc,pic)\ 
     VALUES (%s, %s, %s, %s, %s, %s)", 

       (item['title'][0], 
       item['area'][0], 
       item['date'][0], 
       item['sclass'][0], 
       item['desc'][0], 
       item['pic'][0]) 
       )  

我的MySQL版本是5.6 .17和mysql-python版本是1.2.5_

回答

1

DESCreserved keyword in MySQL。如果你要命名列標識符DESC必須敷在蜱:

tx.execute(
    "INSERT INTO raw (title,area,date,sclass,`desc`,pic)\ 
    VALUES (%s, %s, %s, %s, %s, %s)", 

然而,一個更好的解決辦法是不使用保留關鍵字作爲列標識符,因爲它可能會導致混亂和潛在的其他地方的錯誤(加上完整的「描述」一詞更加清晰,使得代碼更易於維護)。

tx.execute(
    "INSERT INTO raw (title,area,date,sclass,description,pic)\ 
    VALUES (%s, %s, %s, %s, %s, %s)", 
+0

BIG THX!我太粗心了 – Will 2015-03-19 13:27:38