Iw4n
Iw4n

Reputation: 35

Inserting csv into MySQL database with python library mysql.connector

I have trouble with insert of csv data into MySQL tabel with mysql.connector .

The code I use looks like this :

import mysql.connector
import csv

andreport = 'testowa.csv'
cnx = mysql.connector.connect(
    user='xxxxx',
    password='xxxxx',
    host='xxxxxx',
    database='xxxxx')

cursor = cnx.cursor()

with open(andreport, 'r') as csv_data:
    for row in csv_data:
        cursor.execute(
            "INSERT INTO flex(date, Store, Vendor, Shelf)"
            "VALUES({},{},{},{})", row)
cnx.commit()
cursor.close()
cnx.close()
print("Done")

The error I get :

C:\Users\Iw4n\PycharmProjects\Learning\venv\Scripts\python.exe C:/Users/Iw4n/PycharmProjects/Learning/Orange_android_MySQL_insertion.py
Traceback (most recent call last):
  File "C:/Users/Iw4n/PycharmProjects/Learning/Orange_android_MySQL_insertion.py", line 15, in <module>
    cursor.execute(
  File "C:\Users\Iw4n\PycharmProjects\Learning\venv\lib\site-packages\mysql\connector\cursor.py", line 551, in execute
    self._handle_result(self._connection.cmd_query(stmt))
  File "C:\Users\Iw4n\PycharmProjects\Learning\venv\lib\site-packages\mysql\connector\connection.py", line 490, in cmd_query
    result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
  File "C:\Users\Iw4n\PycharmProjects\Learning\venv\lib\site-packages\mysql\connector\connection.py", line 395, in _handle_result
    raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1064 (42000): 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 '},{},{},{})' at line 1

When i wrapped {} into '' , as many rows as were in csv been inserted into datbase as {},{}

same story goes for %s if I use it , i got the same error as above, when it's wrapped in '' , %s is insetred into database. I also found information to add f in fron of "INSERT~ but it did not help.

Can anyone give me some suggestion on how to overcome this and correctly insert data to MySQL ?

Final code that is working as intended :

import mysql.connector
import csv

andreport = 'testowa.csv'
cnx = mysql.connector.connect(
    user='xxxxx',
    password='xxxxx',
    host='xxxxx',
    database='xxxxx')

cursor = cnx.cursor()

with open(andreport, mode='r') as csv_data:
    reader = csv.reader(csv_data, delimiter=';')
    csv_data_list = list(reader)
    for row in csv_data_list:
        cursor.execute("""
                   INSERT INTO flex(
                   date, Agency, MediaSource, Campaign)
                   VALUES(%s,%s,%s,%s)""",
                    (row[0], row[1], row[2], row[3]))
cnx.commit()
cursor.close()
cnx.close()
print("Done")

Upvotes: 2

Views: 3465

Answers (2)

Mahrez BenHamad
Mahrez BenHamad

Reputation: 2068

I'm guessing that seems the problem is that you passed one argument (row) instead of four. So try this:

  cursor.execute("""
            INSERT INTO flex(date, Store, Vendor, Shelf)
            VALUES(%s,%s,%s,%s)""",(row[0], row[1], row[2], row[3], ))

Upvotes: 3

Sam Gaudet
Sam Gaudet

Reputation: 61

Looking at the documentation for MySQLCursor.excute() method, it seems like adding some %s as the parameters in your insert statement might fix this?

import mysql.connector
import csv

andreport = 'testowa.csv'
cnx = mysql.connector.connect(
    user='xxxxx',
    password='xxxxx',
    host='xxxxxx',
    database='xxxxx')

cursor = cnx.cursor()

insert_statement = (
    "INSERT INTO flex(date, Store, Vendor, Shelf)"
    "VALUES (%s, %s, %s, %s)"
)

with open(andreport, mode='r') as csv_data:
    reader = csv.reader(csv_data, delimiter=';')
    csv_data_list = list(reader)
    for row in csv_data_list:
        cursor.execute(insert_statement, row)
cnx.commit()
cursor.close()
cnx.close()
print("Done")

Let me know if this gets you anywhere, or if you see a new error!

Edit: updated CSV reading to convert to a list.

Upvotes: 3

Related Questions