将CSV数据加载到Python中的MySQL中

将CSV数据加载到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"