2016-12-05 145 views
1

我對Python的新usign MySLQdb我有這樣的代碼:_mysql_exceptions.ProgrammingError:(1064,「您的SQL語法錯誤;)

for row in csv_reader: 
    insert = """INSERT INTO %s 
       VALUES (DEFAULT, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) """ 
    cursor.execute(insert, (nome_tabela, row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9], row[10], row[11], row[12], row[13], row[14])) 

但是,當我執行,我有這個以下錯誤: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 ''Aquecimento'\n\t\t\t\t\tVALUES (DEFAULT, 'c00010', 'Dorm1', '0.0', '0.0', '0.0', '3.4' at line 1")

我想象的錯誤conected表中的名字,但我不知道這一點

+0

錯誤來自使用'''而不是反引號標識符。不知道如何在python中處理這個問題。 – Sirko

+0

佔位符通常不能用於*標識符*(表格和列名稱等)。如果這是一個本地準備好的語句,那麼數據庫API會拒絕它。 – deceze

回答

1

據我所知,mysql-python不處理表名稱替換:它盲目地增加在所有變量周圍引用引號並在SQL注入時再次轉義數據

你最好的運氣是自己字符串連接在一起,但你需要有關name_tabela在這種情況下,內容格外謹慎

insert = (
     "INSERT INTO %s" % name_tabela 
     + " VALUES (DEFAULT, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)" 
) 
cursor.execute(insert, (row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9], row[10], row[11], row[12], row[13], row[14])) 

順便說一句,你可以simplfy您execute秒ARG這種方式:

cursor.execute(insert, row[:15]) 
# or even this if the `row` has exactly 15 values 
cursor.execute(insert, row)