无法使用python插入mysql表

时间:2018-10-16 02:48:19

标签: python mysql csv

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

一共有五列(id(自动增量,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表中插入行

1 个答案:

答案 0 :(得分:0)

假设您的CSV有四列,

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

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