在 Python 中将 CSV 数据加载到 MySQL

2021-11-20 00:00:00 python mysql

不确定我在这里遗漏了什么,但此代码运行时没有任何错误消息,但表中没有任何内容.我正在将三列中的 CSV 值加载到 mysql 表中

Not sure what I'm missing here but this code runs without any error message, but there's nothing in the table. I'm loading a CSV values in three columns into mysql table

import csv
import MySQLdb

mydb = MySQLdb.connect(host='localhost',
    user='root',
    passwd='',
    db='mydb')
cursor = mydb.cursor()

csv_data = csv.reader(file('students.csv'))
for row in csv_data:

    cursor.execute('INSERT INTO testcsv(names, \
          classes, mark )' \
          'VALUES("%s", "%s", "%s")', 
          row)
#close the connection to the database.
cursor.close()
print "Done"

如果有其他人可以看看,我们将不胜感激.

Would appreciate if someone else could have a look.

推荐答案

我觉得你必须把 mydb.commit() 全部插入进去.

I think you have to do mydb.commit() all the insert into.

类似的东西

import csv
import MySQLdb

mydb = MySQLdb.connect(host='localhost',
    user='root',
    passwd='',
    db='mydb')
cursor = mydb.cursor()

csv_data = csv.reader(file('students.csv'))
for row in csv_data:

    cursor.execute('INSERT INTO testcsv(names, \
          classes, mark )' \
          'VALUES("%s", "%s", "%s")', 
          row)
#close the connection to the database.
mydb.commit()
cursor.close()
print "Done"

相关文章