首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法从python2.7中的.csv文件中插入数据库中的记录(使用El Capitan )

问无法从python2.7中的.csv文件中插入数据库中的记录(使用El Capitan )
EN

Stack Overflow用户
提问于 2017-01-28 14:25:27
回答 1查看 40关注 0票数 0

我希望从.csv导入数据,并使用Python2.7.13将其加载到MySQL表中。我没有收到任何错误,但是没有将行插入到表中。我尝试了硬编码查询,并成功地插入了它。

我尝试过的代码,没有插入数据:

代码语言:javascript
复制
import csv
import MySQLdb


mydbh = MySQLdb.connect(host='**', user='**', passwd='**', db='**')
cursor = mydbh.cursor()

csv_data = csv.reader(file('load_1.csv'))

for row in csv_data:
    print row
    try:    
        cursor.execute("INSERT INTO `VEG_STARTERS`(`menu_cd`, `cuisene_type`, `cuisine_cd`, `cuisine_name`, `price`, `update_datetime`) VALUES ( %s, %s, %s, %s, %s, now());", row)
        mydbh.commit()
    except:
        print "Unable to insert data"

print "%d rows were inserted" % cursor.rowcount

cursor.close()

产出:

无法插入数据的4\tVEG_ST\tVEG_ST_1\tROTI芯片\t 100\t无法插入数据'4\tVEG_ST\tVEG_ST_2\tSPICY CHEESY POPS\T 140\t‘无法插入数据'4\tVEG_ST\tVEG_ST_3\tMINI TACO炸弹\T 200\t’无法插入数据'4\tVEG_ST\tVEG_ST_4\tCROSTINIS\t200\t‘无法插入数据0行。

有效的硬编码查询:

代码语言:javascript
复制
import csv
import MySQLdb


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

cursor.execute("INSERT INTO VEG_STARTERS(menu_cd, cuisene_type, cuisine_cd, cuisine_name, price, update_datetime) VALUES ( 4, 'VEG_ST', 'VEG_ST_6', 'TEST', 100.15, now())")
mydbh.commit()

print "%d rows were inserted" % cursor.rowcount

cursor.close()

我在网上搜索,但找不到解决问题的办法。任何建议都是非常感谢的。谢谢。

EN

回答 1

Stack Overflow用户

发布于 2017-01-28 14:38:28

您的值是选项卡分隔的(\t)。尝试:

代码语言:javascript
复制
csv_data = csv.reader(file('load_1.csv'), delimiter='\t')

读取csv文件时。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41910876

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档