excel表数据导入mysql数据库

使用xlrd模块

目前xrld最新版为2.0.1,不支持.xls文件,1.2.0版支持.xls文件

pip3 install xlrd == 1.2.0

1、数据库test中test_excel表,id为自增主键

           

 2、F盘中有一张excel表--code_db.xlsx,数据如下

 

 3、通过代码把表数据插入数据库中

import xlrd
import pymysql


# 获取excel表对象
def open_excel():
    try:
        # 使用xlrd创建一个工作薄对象
        table = xlrd.open_workbook(r'F:\code_db.xlsx')
    except:
        print("open excel file failed!")

    try:
        # 根据工作表的名称创建表格对象
        sheet = table.sheet_by_name('Sheet1') #通过表名称获取Sheet对象
        return sheet
    except:
        print("locate worksheet in excel failed!")


# 连接数据库
def mysql_link(de_name):
    try:
        db = pymysql.connect(host="127.0.0.1", user="root",
                             passwd="数据库密码",
                             db=de_name,
                             charset='utf8')
        return db
    except:
        print("could not connect to mysql server")

db = mysql_link("test")

# 从excel表中取数据插入数据库中
def insert_data():
    sheet = open_excel()
    cursor = db.cursor() #创建游标对象
    # sheet.nrows:获取最大的行数
    for i in range(1,sheet.nrows):#第1行是标题名,从第2行开始读取数据

        age = sheet.cell(i,1).value  #第i行第2列
        name = sheet.cell(i,2).value #第i行第3列
        value = (age,name)
        sql = "insert into test_excel(age,name) values(%s,%s) "
        cursor.execute(sql,value)
        db.commit()
    cursor.close()

'''
数据库查询
'''
def search_count():
    cursor = db.cursor()
    select = "select * from test_excel"
    cursor.execute(select)
    line_count = cursor.fetchone()
    print(line_count) #(98, 23, 'ffisf451sfsffssfsf62')

insert_data() #插入表数据
search_count() #查询表数据
db.close() #关闭数据库连接

结果如下:

 注:python连接sql server数据库

使用pymssql模块进行连接

#首先根据python版本安装对应的pymssql
import pymssql
conn = pymssql.connect(server,user,password,database)

 

posted @ 2021-11-14 21:17  zh_小猿  阅读(568)  评论(0编辑  收藏  举报