簡體   English   中英

Python中MySQL語句中的語法錯誤(1064)

[英]Syntax error (1064) in MySQL statement in Python

我正在嘗試將所有數據插入到我創建的表中。 這是我的代碼的相關部分:

    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", ....

我還嘗試用反引號將列名稱包裝起來,但這沒有幫助。

不能對表名進行參數設置。 您必須以字符串格式添加它。

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'])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM