无法使用python插入mysql表

8hhllhi2  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(387)

我正在尝试使用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表中插入行

sqxo8psd

sqxo8psd1#

假设csv有四列,

mycursor.execute("INSERT INTO opm (Event, Edition, Subscription, Daystogo) VALUES (%s,%s,%s,%s)", row)

应该起作用(第二个参数需要是一个列表或元组,其中包含要绑定到占位符的元素;因为有四个占位符,所以需要一个四元素列表或数据元组(不是数据类型!)。

相关问题