I have the following error on my 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")
Here is a portion of my code that causes the error:
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))
And This is my 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))"
)
This looks right to me, but the IDE keep saying that there is a syntax error.
The error is happening because one of the values that you are passing for insert contains a single quote. MySQL cannot tell disambiguate the embedded quote from the surrounding quotes.
'Kristopher O'Connell'
Here is an alternative syntax using bind parameters, that should work with 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)
)
With this syntax, your database driver handles escaping automatically under the hood. This is also a safer syntax, that protects against SQL injection.
NB: depending on the API that you are using, this might also be:
cursor.execute(
"INSERT INTO LSU.Student
(Semail, Spassword, Sname, Sage, Sgender, Smajor, Sstreet, Szipcode)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
(a, b, c, d, e, f, g, h)
)
Try taking the '
off from all the variables inside the values section.
Such as values (%s, %s, %s .....)
instead of values ('%s', '%s', ...)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.