首页 > 解决方案 > 无法使用python插入mysql表

问题描述

我正在尝试使用 python 中的 csv 文件在我的 sql 表中插入行。

有五列(id(autoincrement, primary, int),Event(int), Edition(int), Subscription(varchar), Daystogo(varchar)

我的 csv 有 4 列(事件、版本、订阅、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表中插入行

标签: pythonmysqlcsv

解决方案


假设您的 CSV 有四列,

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

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


推荐阅读