我的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))
这是我的创建表:
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一直在说语法错误。
答案 0 :(得分:0)
'Kristopher O'Connell'中的单引号(')是否会干扰查询?
答案 1 :(得分:0)
请考虑parameterization,这是行业内最好的建议和推荐方法,可避免恶意用户进行SQL注入;引用可能破坏查询执行的附件和特殊字符;以及无法理解/无法维护的代码,因为数据与代码混合在一起。
# PREPARED STATEMENT (ALL PLACEHOLDERS USING UNQUOTED %s PLACEHOLDERS, NO DATA)
sql = """INSERT INTO LSU.Student (Semail, Spassword, Sname, Sage, Sgender, Smajor, Sstreet, Szipcode)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
"""
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']):
# QUERY EXECUTION
cursor.execute(sql, (a, b, c, d, e, f, g, h))
即使您正在从数据帧中进行迭代,也可以考虑使用pandas的DataFrame.values方法来使用executemany
。这样可以避免for
和zip
循环:
# PREPARED STATEMENT
sql = """INSERT INTO LSU.Student (Semail, Spassword, Sname, Sage, Sgender, Smajor, Sstreet, Szipcode)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
"""
# EXECUTE PARAMETERIZED QUERY
sql_cols = ['Email', 'Password', 'Full Name', 'Age', 'Gender', 'Major', 'Street', 'Zip']
cursor.executemany(sql, df_stu[sql_cols].values.tolist())
conn.commit()