[英]1064, “You have an error in your SQL syntax” inserting in MySql
我的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))
這是我的CREATE TABLE:
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一直說有語法錯誤。
發生錯誤的原因是您為insert傳遞的值之一包含單引號。 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)
)
嘗試采取的'
從值段內所有的變量了。
比如values (%s, %s, %s .....)
而不是values ('%s', '%s', ...)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.