1064,在MySql中插入“ SQL语法有错误”

时间:2019-04-03 19:35:01

标签: python mysql sql pandas pycharm

我的IDE出现以下错误:

  

MySQLdb._exceptions.ProgrammingError:(1064,“您的SQL语法有错误;请查看与您的MySQL服务器版本相对应的手册,以获取在'2102@lionstate.edu','88zlsj5j'附近使用的正确语法。 ,'Kristopher O'Connell','21','F','CMPSC','77'在第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))

这是我的创建表:

cursor.execute(
        "CREATE TABLE IF NOT EXISTS LSU.Student (
            Semail CHAR(50), 
            Spassword CHAR(20), 
            Sname CHAR(50),
            Sage INT, 
            Sgender CHAR(5), 
            Smajor CHAR(50), 
            Sstreet CHAR(50), 
            Szipcode INT, 
            PRIMARY KEY (Semail))"
)

这对我来说似乎很正确,但是IDE一直在说语法错误。

2 个答案:

答案 0 :(得分:0)

发生错误,因为您要传递给插入的值之一包含单引号。 MySQL无法分辨出嵌入式报价与周围的报价。

'Kristopher O'Connell'

这是使用绑定参数的另一种语法,应该与python一起使用:

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

使用此语法,您的数据库驱动程序将自动在后台进行转义。这也是一种更安全的语法,可以防止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)
)

答案 1 :(得分:0)

尝试从值部分的所有变量中删除'

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