_mysql_exceptions.OperationalError:(1366,“不正确的整数值:第1行第'ID'列的'%s'”)

时间:2017-01-09 18:55:19

标签: python csv mysql-python

我正在尝试使用python脚本将.csv中的数据插入到Mysql数据库中。

我使用的python脚本

import csv
import MySQLdb

db = MySQLdb.connect(host='localhost',user='root',passwd='password',db='EfficientBazzar')
cursor = db.cursor()

csv_data = csv.reader(file('products.csv'))
for row in csv_data:
    cursor.execute('INSERT INTO vendor_price_list(ID,Vendor,productname,productcode,unit,weight,price)' 'VALUES("%s","%s","%s","%s","%s","%s","%s")')

db.commit()
cursor.close()
print "Done"

2 个答案:

答案 0 :(得分:1)

您忘记将行数据插入更新查询。

替换:

'VALUES("%s","%s","%s","%s","%s","%s","%s")'

使用:

'VALUES("%s","%s","%s","%s","%s","%s","%s")' % tuple(row)

答案 1 :(得分:0)

实际上甚至更好,请考虑参数化查询:

cursor.execute('INSERT INTO vendor_price_list(ID,Vendor,productname,productcode,unit,weight,price)' + \
               ' VALUES(%s,%s,%s,%s,%s,%s,%s)', row)

更快的是直接来自带有MySQL LOAD DATA INFILE的csv的批量命令(假设服务器实例设置允许):

cursor.execute("LOAD DATA INFILE '/path/to/products.csv'" + \
               " INTO TABLE vendor_price_list" + \
               " FIELDS TERMINATED BY ',' ENCLOSED BY '\"'" + \
               " LINES TERMINATED BY '\n' IGNORE 1 ROWS")