我希望从.csv导入数据,并使用Python2.7.13将其加载到MySQL表中。我没有收到任何错误,但是没有将行插入到表中。我尝试了硬编码查询,并成功地插入了它。
我尝试过的代码,没有插入数据:
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行。
有效的硬编码查询:
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()我在网上搜索,但找不到解决问题的办法。任何建议都是非常感谢的。谢谢。
发布于 2017-01-28 14:38:28
您的值是选项卡分隔的(\t)。尝试:
csv_data = csv.reader(file('load_1.csv'), delimiter='\t')读取csv文件时。
https://stackoverflow.com/questions/41910876
复制相似问题