_mysql数据库_异常。编程错误:(1064,“SQL语法中有错误;)

2024-10-01 13:35:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python的新用户MySLQdb。我有这个代码:

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")

我认为错误与表名有关,但我不确定。在


Tags: csvtheto代码用户indefaultfor
1条回答
网友
1楼 · 发布于 2024-10-01 13:35:51

Afaik,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]))

顺便说一下,您可以通过以下方式简化execute第二个参数:

^{pr2}$

相关问题 更多 >