Python 我编写了将列表中的值插入mysql数据库的代码,但出现了编程错误
你有几个问题。语法错误是由缺少括号引起的:Python 我编写了将列表中的值插入mysql数据库的代码,但出现了编程错误,python,mysql,Python,Mysql,你有几个问题。语法错误是由缺少括号引起的: import MySQLdb import mysql.connector dbb_connection MySQLdb.connect(host="localhost",user="root",passwd="root",database="translation",use_unicode=True,charset="utf8") dbb_cursor = dbb_connection.cursor() for item in eel
import MySQLdb
import mysql.connector
dbb_connection MySQLdb.connect(host="localhost",user="root",passwd="root",database="translation",use_unicode=True,charset="utf8")
dbb_cursor = dbb_connection.cursor()
for item in eels:
print(item)
student_sql_query = ("INSERT INTO eng (Eng) VALUES %s" % (item))
dbb_cursor.execute(student_sql_query)
dbb_connection.commit()
print(dbb_cursor.rowcount, "Record Inserted")
因此,如果item
是一个整数,比如说7
,您的SQL查询将变成:
student_sql_query = ("INSERT INTO eng (Eng) VALUES (%s)" % (item))
但如果item是字符串,“boat”
?那么你会:
INSERT INTO eng (Eng) VALUES (7)
这显然是错误的。因此,如果您知道您有字符串值,您可能会尝试执行以下操作:
INSERT INTO eng (Eng) VALUES (boat)
除非item
中有单引号,否则这可能会起作用。但还有一个更大的问题。如果项
的值是用户提供的,则可能会受到SQL注入攻击(请查看此项)。查询的方式如下所示:
student_sql_query = ("INSERT INTO eng (Eng) VALUES ('%s')" % (item))
在SQL查询中使用
%s
作为值的占位符,然后传递一个列表
或一个元组
,其中包含调用执行
编程错误:(1064,“您的SQL语法有错误;请查看与您的MySQL服务器版本对应的手册,以了解在“2018年1月-2019年3月年度报告”第1行附近使用的正确语法”。您不得在SQL查询中使用%
!
student_sql_query = "INSERT INTO eng (Eng) VALUES (%s)"
dbb_cursor.execute(student_sql_query, (item,))