【问题标题】:_mysql_exceptions.OperationalError: (1366, "Incorrect integer value: '%s' for column 'ID' at row 1")_mysql_exceptions.OperationalError:(1366,“不正确的整数值:第 1 行的列 'ID' 的 '%s'”)
【发布时间】:2017-05-24 02:59:30
【问题描述】:

我正在尝试使用 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"

【问题讨论】:

    标签: python csv mysql-python


    【解决方案1】:

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

    替换:

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

    与:

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

    【讨论】:

    • 很高兴能帮上忙!请接受答案然后;P。
    • 嗨,你能解释一下你要插入什么吗?
    【解决方案2】:

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

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

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

    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")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-11
      • 2020-05-31
      相关资源
      最近更新 更多