在 Python 中将 CSV 数据加载到 MySQL [英] Load CSV data into MySQL in Python

查看:30
本文介绍了在 Python 中将 CSV 数据加载到 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"

这篇关于在 Python 中将 CSV 数据加载到 MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆