2017-04-14 11 views
0

先生得到錯誤,同時使用python導入Excel數據導入MySQL只一行插入

我試圖導入使用Python和視頻教程的幫助Excel數據導入MySQL,但我有以下問題:

僅在Excel文件中的第一行插入MySQL和得到以下錯誤

cursor.execute(query, values) line 179 in execute 

這裏是我的代碼

import xlrd 
import MySQLdb 
book=xlrd.open_workbook("C:\Python27\mygdata.xls") 
sheet=book.sheet_by_name("Sheet1") 

database=MySQLdb.connect(host="Localhost", user="root", passwd="sharan246", db="test1") 
cursor=database.cursor() 
query=""" INSERT INTO omrdata (regno,name,subject,barcode,flag1) values (%s,%s,%s,%s,%s)""" 
for r in range(1, sheet.nrows): 
    regno = sheet.cell(r, 0).value 
    name= sheet.cell(r, 1).value 
    subject=sheet.cell(r, 2).value 
    barcode=sheet.cell(r, 3).value 
    flag1=sheet.cell(r, 4).value 
    values=(regno,name,subject,barcode,flag1) 
    cursor.execute(query, values) 
    cursor.close() 
    database.commit() 
    database.close() 
    print "" 
    print "All done bye for now" 
    print "" 
    columns=str(sheet.ncols) 
    print"i Just Imported" 

請幫我

+1

'cursor.execute(...)'之後的所有行應該在'for'循環之外。剛剛插入第一行後,您正在關閉連接和數據庫。 – AKS

回答

0

您關閉光標cursor.close()以及database.close()在for循環中,但在開始時打開它只有一次。嘗試將這些行移出for循環,看看它是否會有所幫助。

+0

謝謝你這麼多先生 –

+0

先生如果你不介意多一個問題我如何得到導入記錄的計數 –

+0

@sharankumar查看'cursor.rowcount' https://www.python.org/dev/peps/pep-0249 /#行數 – Vor