0

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

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.