有一个包含要使用python插入到mysql的表中的数据的文件。我使用“ with open”从文件中检索了数据并将其转换为list.so,现在在列表中,元素为字符串,而我想要将字符串更改为元组,以便我可以从中检索数据到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
答案 0 :(得分:0)
每行都有一个列表,其中包含CSV文件的每一行。然后,您需要遍历所有行并再次对分隔符(',')进行分割:
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()