2017-01-09 63 views
0

我試圖從.csv插入我的數據到Mysql數據庫使用python腳本。我用它_mysql_exceptions.OperationalError:(1366,「錯誤的整數值:'%s'列'ID'在第1行)

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" 

回答

0

Python腳本你忘了該行數據插入到你的更新查詢。

替換:

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

有:

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

謝謝,它的工作 –

+0

很高興我能幫到你!那麼請接受答案; P。 –

0

其實更好,考慮參數化查詢:

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") 
相關問題