简体   繁体   中英

error while doing insert data from a file to mysql using python

there is a file containing data that I want to insert into table in mysql using python.I retrieved the data from file using "with open" and converted it to a list.so now in the list the elements are string and i want to change string to tuple so that i can retrieve the data from this to mysql.

    import mysql.connector


    with open("/home/ninky/com.csv", "r") as fp:
        content = fp.read()
    lines = content.split("\n")
    print(lines)

        myconn = mysql.connector.connect(host="localhost", user="root", database="EMPSALARY" 
        cur = myconn.cursor()
        db = "insert into PERSON(name,age,year)values(%s,%s,%s)"
        myconn = cur.execute(db, lines)
        myconn.close()
result:
-----------
['deepak,29,2019', 'ninky,29,2010', 'suraj,29,2020', 'pratap,30,2018', '']
deepak,29,2019
ninky,29,2010
suraj,29,2020
pratap,30,2018
 Traceback (most recent call last): File "/home/ninky/PycharmProjects/new/csv_db.py", line 23, in <module> cur.execute(db, lines) File "/usr/local/lib/python3.6/dist-packages/mysql/connector/cursor.py", line 543, in execute "Not all parameters were used in the SQL statement") mysql.connector.errors. ProgrammingError: Not all parameters were used in the SQL statement 
Process finished with exit code 1

In lines what you have is a list containing each line of your CSV file. Then, you need to iterate through all lines and do a split again on your separator (','):

import mysql.connector

with open("/home/ninky/com.csv", "r") as fp:
    content = fp.read()
lines = content.split("\n")
print(lines)


myconn = mysql.connector.connect(host="localhost", user="root", database="EMPSALARY")
cur = myconn.cursor()

db = "insert into PERSON (name,age,year) values (%s,%s,%s)"
for l in lines:
    data=l.split(',')
    cur.execute(db, data)
myconn.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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