Python中MySQL语句中的语法错误(1064)

时间:2013-06-23 01:29:36

标签: python mysql

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

    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 个答案:

答案 0 :(得分: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'])