python将excel的数据导入mysql

来源:互联网 发布:京东比价软件 编辑:程序博客网 时间:2024/05/23 09:45

主要引用的包有:

MySQLdb
xlrd
代码为:

# coding=utf-8import MySQLdbimport xlrdbook = xlrd.open_workbook("f:\\test\\excel.xlsx")sheet = book.sheet_by_name("Sheet1")conn= MySQLdb.connect(        host='localhost',        port = 3306,        user='root',        passwd='123456',        db ='test',        )cursor = conn.cursor()sql = "insert into test1(name,age) values(%s,%s)"# 循环获取数据并保存数据for r in range(1, sheet.nrows):        name = sheet.cell(r,0).value        age = sheet.cell(r,1).value        cursor.execute(sql,(name,age))cursor.close()conn.commit()conn.close()