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

2024-10-02 00:26:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从.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()

我在网上搜索,但找不到解决问题的方法。任何建议都将不胜感激。谢谢


Tags: csvtoimportdatacdcursorinsertst

热门问题