1064“You have a error in your SQL syntax”在MySq中插入

2024-04-20 00:44:40 发布

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

我的IDE有以下错误:

MySQLdb._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 '2102@lionstate.edu', '88zlsj5j', 'Kristopher O'Connell', '21', 'F', 'CMPSC', '77' at line 1")

以下是导致错误的部分代码:

for a, b, c, d, e ,f, g, h in zip(df_stu['Email'], df_stu['Password'], df_stu['Full Name'], df_stu['Age'], df_stu['Gender'], df_stu['Major'], df_stu['Street'], df_stu['Zip']):
    cursor.execute("INSERT INTO LSU.Student (Semail, Spassword, Sname, Sage, Sgender, Smajor, Sstreet, Szipcode) "
                   "VALUES ('%s', '%s', '%s', '%d', '%s', '%s', '%s', '%d')" % (a, b, c, d, e, f, g, h))

这是我的创建表:

^{pr2}$

这在我看来是正确的,但是IDE一直说存在语法错误。在


Tags: thetoinyoudfforyourhave
2条回答

尝试从values部分中的所有变量中去掉'。在

例如values (%s, %s, %s .....)而不是values ('%s', '%s', ...)

发生错误是因为您传递给insert的其中一个值包含单引号。MySQL无法区分嵌入引号和周围引号的消歧。在

'Kristopher O'Connell'

下面是一种使用绑定参数的替代语法,它应该适用于python:

^{pr2}$

使用这种语法,您的数据库驱动程序可以在后台自动处理转义。这也是一种更安全的语法,可以防止SQL注入。在

注意:根据您使用的API,也可能是:

cursor.execute(
    "INSERT INTO LSU.Student 
        (Semail, Spassword, Sname, Sage, Sgender, Smajor, Sstreet, Szipcode)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
        (a, b, c, d, e, f, g, h)
)

相关问题 更多 >