读取Excel表插入MySQL数据库


思路解读:
  1. 读取Excel中你要存入数据库的数据
  2. python3的环境下导入pymysql,执行MySQL插入语句,插入成功(以插入小说的评论为例)
# -*- coding: utf-8 -*-
import pymysql
import xlrd


def open_excel(file):
    try:
        data = xlrd.open_workbook(file)
        return data
    except Exception as e:
        print(str(e))

def excel_table_byindex():
# 此处填写你的excel路劲
    data = open_excel('Excel.xlsx')
    table = data.sheet_by_name(u'Sheet1') #通过名称获取
    nrows = table.nrows #行数
    colnames =  table.row_values(10) #某一行数据

    db = pymysql.connect(
        host='你的ip地址',
        database='数据库名称',
        user='root',
        password='数据库密码',
        port=3306,
        charset='utf8',
    )

    #此处填写你的Excel表格中导入数据的行数
    for i in range(nrows):
        #此处代表行,1代表列
        bookname = table.cell(i,1).value
        comments = table.cell(i, 2).value
        novel_id = int(novel_id)
        #此方法为将查出的数据转为str类型
        bookname = db.escape_string(bookname)
        comments = db.escape_string(comments)
        # 此处打开Mysql,执行sql插入语句
        with db.cursor() as cursor:
            sql = "INSERT INTO comments (bookname,comments)VALUES('%s','%s');" % \
                  ( bookname, comments)
            print(sql)
            db.ping(reconnect=True)
            cursor.execute(sql)
            db.commit()
            db.close()


def main():
    tables = excel_table_byindex()

if __name__=="__main__":
    main()

你可能感兴趣的:(读取Excel表插入MySQL数据库)