2013-06-23 46 views
1

我試圖將所有數據都插入到我創建的表中。這是我的代碼的相關部分:Python中的MySQL語句中的語法錯誤(1064)

rows_inserted = 0 
    table_name = "mytable" 

    for row in ordered: # ordered is a list of lists. it contains all my data 
     sql = ("INSERT IGNORE INTO %s (ID, A, B, C, D, E, F) VALUES (%s, %s, %s, %s, %s, %s, %s)") 

     rows_inserted += cursor.execute(sql, (table_name, 1, row[0], row[1], row[2], row[3], row[4], row[5])) 

    print(rows_inserted) # to verify that all the records have been inserted to the table 

當我在我的服務器上運行腳本,我收到以下錯誤:

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 ''mytable' (ID, A, B, C, D, E, F) VALUES (1, "QP123", .... 

我也試圖與反引號包住列名,但它沒沒有幫助。

回答

1

表名不能被參數化。你必須添加它與字符串格式。

sql = """INSERT IGNORE INTO {t} (ID, A, B, C, D, E, F) 
     VALUES (%s, %s, %s, %s, %s, %s, %s)""".format(t=table_name) 
rows_inserted += cursor.execute(sql, (1, row[0], row[1], row[2], row[3], row[4], row[5])) 

我不知道在哪裏,這是記錄,但你可以看到這通過嘗試是正確的:

cursor = connection.cursor() 
sql = 'CREATE TABLE %s' 
cursor.execute(sql, ['test']) 
+0

複製你的代碼後,我仍然得到同樣的錯誤。你看到我的代碼有什麼問題嗎?錯誤是在同一行中。 – tempy

+0

您是否使用MySQLdb作爲數據庫適配器?這個錯誤再次表示'接近''mytable'(ID,A,B,C,D,E,F)VALUES(1,「QP123」,....'?是否可以將任何列名誤認爲MySQL的關鍵字? – unutbu

+0

是的,我使用的是MYSQLdb,錯誤是一樣的,是的,我的列名不能被誤認爲是MySQL的關鍵字,除了'ID'之一,但我也嘗試用反斜槓包裝它們,認爲應該防止這種情況 – tempy