2017-04-14 61 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