简体   繁体   English

mysql插入csv文件在python中不起作用

[英]mysql insert into csv file not working in python

I have tried many times and searched all over the internet and this is still not working for me.我已经尝试了很多次并在整个互联网上进行了搜索,但这仍然不适合我。 I am trying to read from a csv file and insert data into a database with python.我正在尝试从 csv 文件中读取数据并使用 python 将数据插入到数据库中。 This is my code, and I don't understand why it's not working这是我的代码,我不明白为什么它不起作用

import mysql.connector
import csv
import pandas as pd

with open(r'files\files1.csv') as csv_file:
    csvfile = csv.reader(csv_file, delimiter=';')
    allvalues=[]
    for row in csvfile:
        value = (row[0],row[1],row[2])
        allvalues.append(value)

print(allvalues)

db = mysql.connector.connect(
    host = 'ip',
    user = 'user',
    passwd = 'pass',
    database = 'db',
    auth_plugin='mysql_native_password'
)

cursor = db.cursor()

query = "INSERT INTO table1 (col1, col2, col3) VALUES (%s , %s , %s)"

cursor.execute(query, allvalues)

db.commit()


this gives the following error:这给出了以下错误:

   result = self._cmysql.convert_to_mysql(*params)
_mysql_connector.MySQLInterfaceError: Python type tuple cannot be converted

I also want to mentions that I have tried many other things to insert into the table not only the method above, and everytime I get a different error.我还想提一下,我已经尝试了很多其他的东西来插入到表中,不仅是上面的方法,而且每次我得到不同的错误。

Can someone please tell me how do I do it?有人可以告诉我该怎么做吗? I would really appreciate it我真的很感激

Thank you very much非常感谢

use cursor.executemany(query, allvalues)使用cursor.executemany(query, allvalues)

If you have multiple elements which are saved in a list or tuple then use,如果您有多个元素保存在列表或元组中,请使用,

cursor.executemany(query, list) or cursor.executemany(query, tuple) cursor.executemany(query, list)cursor.executemany(query, tuple)

Or you can use for loop或者你可以使用 for 循环

for value in allvalues:
    cursor.execute(query, value)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM