Reputation: 71
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. 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
Upvotes: 0
Views: 117
Reputation: 57
use 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)
Or you can use for loop
for value in allvalues:
cursor.execute(query, value)
Upvotes: 1