我正在尝试使用python中的csv文件在sql表中插入行。
共有五列(id(autoincrement,primary,int)、event(int)、edition(int)、subscription(varchar)、daystogo(varchar)
我的csv有4列(event、edition、subscription、daystogo)。我想把它们插入表中,让id以自动递增的方式分配。
mydb = mysql.connector.connect(
user='user', password='password',
host='host',
database='opm')
mycursor = mydb.cursor()
csv_data=csv.reader("mycsvfile.csv")
for row in csv_data:
print(row)
mycursor.execute("INSERT INTO opm (Event, Edition, Subscription, Daystogo) VALUES (%s,%s,%s,%s)", (int,int,str, str))
这是我一直收到的错误
csv_data=csv.reader("mycsvfile.csv")
for row in csv_data:
print(row)
mycursor.execute("INSERT INTO opm (Event, Edition, Subscription, Daystogo) VALUES (%s,%s,%s,%s)", (int,int,str, str))
['m']
Traceback (most recent call last):
File "<ipython-input-51-5b5e2c804099>", line 4, in <module>
mycursor.execute("INSERT INTO opm (Event, Edition, Subscription, Daystogo) VALUES (%s,%s,%s,%s)", (int,int,str, str))
File "E:\Data Science\pyWork\PyProjects\Program\lib\site-packages\mysql\connector\cursor.py", line 547, in execute
psub = _ParamSubstitutor(self._process_params(params))
File "E:\Data Science\pyWork\PyProjects\Program\lib\site-packages\mysql\connector\cursor.py", line 430, in _process_params
"Failed processing format-parameters; %s" % err)
ProgrammingError: Failed processing format-parameters; Python 'type' cannot be converted to a MySQL type
对于代码
mycursor.execute("INSERT INTO opm (Event, Edition, Subscription, Daystogo) VALUES (%s,%s,%s,%s)")
错误是
ProgrammingError: 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 '%s,%s,%s,%s)' at line 1
请帮助我如何在mysql表中插入行
1条答案
按热度按时间sqxo8psd1#
假设csv有四列,
应该起作用(第二个参数需要是一个列表或元组,其中包含要绑定到占位符的元素;因为有四个占位符,所以需要一个四元素列表或数据元组(不是数据类型!)。