1

我正在尝试将所有数据插入到我创建的表中。这是我的代码的相关部分:

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

我还尝试用反引号包裹列名,但没有帮助。

4

1 回答 1

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'])
于 2013-06-23T01:30:39.877 回答