我想从.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 CHIPS\t100\t'] Unable to insert data ['4\tVEG_ST\tVEG_ST_2\tSPICY CHEESY POPS\t140\t'] Unable to insert data ['4\tVEG_ST\tVEG_ST_3\tMINI TACO BOMBS\t200\t'] Unable to insert data ['4\tVEG_ST\tVEG_ST_4\tCROSTINIS\t200\t'] Unable to insert data 0 rows were inserted
有效的硬编码查询:
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()
我在网上搜索,但找不到解决问题的方法。任何建议都将不胜感激。谢谢
您的值是用制表符分隔的(
\t
)。尝试:读取csv文件时
相关问题 更多 >
编程相关推荐