多线程将excel数据写入mysql

1.总计有27个excel表的数据,
在这里插入图片描述
将sheet2的前两列的数据写入mysql
在这里插入图片描述
2.查看有多少条数据,总计22245条

# -*- coding: utf-8 -*-
# @Time    : 2020/3/10 11:09
# @Author  : 结尾!!
# @FileName: 统计原始数据总计有多少.py
# @Software: PyCharm

import os

import pandas as pd

excel_list=os.listdir('./日本站分类树/')
print(len(excel_list))

count_row=0
for file_one in excel_list:
    print(file_one)
    # 打开第二个sheet表
    df1 = pd.read_excel(f'./日本站分类树/{file_one}', enconding='utf-8', sheet_name=1)
    print(df1.shape)
    count_row+=df1.shape[0]

print("总计有%d条数据"%count_row)

在这里插入图片描述
3.新建数据库以及表,这里我使用的是,Navicat建的表。数据库就是create database classify ;
在这里插入图片描述
表的结构如下。
在这里插入图片描述
4.写入数据库,我开了两个线程。代码如下;

# -*- coding: utf-8 -*-
# @Time    : 2020/3/10 10:48
# @Author  : 结尾!!
# @FileName: 02-写入日本站分类树.py
# @Software: PyCharm



import pandas as pd


import os
import pymysql
def query_data(sql_str):

    # 连接数据库
    conn = pymysql.connect(
        host='127.0.0.1',
        user='root',
        port=3306,
        password='1234',
        db='classify',  #类目的数据库
        charset='utf8'
    )

    # 创建游标
    cursor = conn.cursor()
    # 书写sql语句

    # #执行sql语句
    try:
        cursor.execute(sql_str)
        # 提交连接
        conn.commit()
    except:
        conn.rollback()
    # 关闭游标,关闭连接
    cursor.close()
    conn.close()


def task1(excel_list):
    for file_one in excel_list:
        print(file_one)
        # 打开第二个sheet表
        df1 = pd.read_excel(f'./日本站分类树/{file_one}', enconding='utf-8', sheet_name=1)
        print(df1.head())
        for index,each in df1.iterrows(): #读取dataframe的每一行的值
            try:
                sql_str= "INSERT INTO Japan (node_id, node_path) VALUES ( '%s' ,' %s');"%(str(each.iloc[0]),each.iloc[1])
                print(sql_str)
                query_data(sql_str)  #执行sql语句
            except Exception as e:
                print(e)


def task2(excel_list):
    for file_one in excel_list:
        print(file_one)
        # 打开第二个sheet表
        df1 = pd.read_excel(f'./日本站分类树/{file_one}', enconding='utf-8', sheet_name=1)
        print(df1.head())
        for index,each in df1.iterrows(): #读取dataframe的每一行的值
            try:
                sql_str= "INSERT INTO Japan (node_id, node_path) VALUES ( '%s' ,' %s');"%(str(each.iloc[0]),each.iloc[1])
                print(sql_str)
                query_data(sql_str)  #执行sql语句
            except Exception as e:
                print(e)


#使用多线程进行
import threading

excel_list=os.listdir('./日本站分类树/')
print(len(excel_list))
#线程执行的函数名不能一样。
t1 = threading.Thread(target=task1,args=(excel_list[:12],) )# 线程一,Thread函数有两个参数,第一个是要调用的线程函数,第二个是要给所调用的线程函数所传的参数,以元组的形式传入,如果只有一个参数,则必须在后面加上一个',’ ,要不会报错。
t2 = threading.Thread(target=task2, args=(excel_list[12:],))# 线程二
t1.start()# 开始线程一<br>#  t1.join()
t2.start()  # 开始线程二

运行如下:
在这里插入图片描述
最后插入了21728条数据。

在这里插入图片描述
4.数据少了517条。
查找什么原因,看一下少的是哪些数据。


import os

import pandas as pd

excel_list=os.listdir('./日本站分类树/')
print(len(excel_list))

import pymysql
def query_data(sql_str):

    # 连接数据库
    conn = pymysql.connect(
        host='127.0.0.1',
        user='root',
        port=3306,
        password='1234',
        db='classify',  #类目的数据库
        charset='utf8'
    )

    # 创建游标
    cursor = conn.cursor()
    # 书写sql语句

    # #执行sql语句
    try:
        cursor.execute(sql_str)
        # 提交连接
        conn.commit()
        data = cursor.fetchall()
    except:
        conn.rollback()
    # 关闭游标,关闭连接
    finally:
        cursor.close()
        conn.close()
        return data


for file_one in excel_list:
    print(file_one)
    # 打开第二个sheet表
    df1 = pd.read_excel(f'./日本站分类树/{file_one}', enconding='utf-8', sheet_name=1)
    print(df1.shape)

    for index, each in df1.iterrows():  # 读取dataframe的每一行的值
        try:
            sql_str = "SELECT * FROM Japan WHERE Node_id=%s ;" %(str(each.iloc[0]))
            # print(sql_str)
            res=query_data(sql_str)  # 执行sql语句
            # print(res)
            if len(res)==0:
                print(sql_str)
        except Exception as e:
            print('错误',e)


对数据库数据进行查找,发现是下面的excel中的数据没有。
jp_books-gurupa-us-subtier_browse_tree_guide.TTH.xls ,少了数据
在这里插入图片描述
进检测,就是少了这一个表格中的数据。
在这里插入图片描述
6.下面进行重新写入。
并将异常跑出查看,,由于字符的引号导致的。
在这里插入图片描述
在这里插入图片描述
将代码重新修改了,之后正常写入了。

import pandas as pd


import os
import pymysql
def query_data(sql_str):

    # 连接数据库
    conn = pymysql.connect(
        host='127.0.0.1',
        user='root',
        port=3306,
        password='1234',
        db='classify',  #类目的数据库
        charset='utf8'
    )

    # 创建游标
    cursor = conn.cursor()
    # 书写sql语句

    # #执行sql语句
    try:
        cursor.execute(sql_str)
        # 提交连接
        conn.commit()
        data = cursor.fetchall()
    except:
        conn.rollback()
    # 关闭游标,关闭连接
    finally:
        cursor.close()
        conn.close()
        return data



def increase_data(file_name):
    df1 = pd.read_excel(f'./日本站分类树/{file_name}', enconding='utf-8', sheet_name=1)
    print(df1.shape)

    for index, each in df1.iterrows():  # 读取dataframe的每一行的值
        try:
            sql_str_1 = "SELECT * FROM Japan WHERE Node_id=%s ;" % (str(each.iloc[0]))
            res = query_data(sql_str_1)  # 执行sql语句
            # print(res)
            if len(res) == 0:
                sql_str = 'INSERT INTO Japan (Node_id, Node_path) VALUES ( "%s" ,"%s");' % (
                str(each.iloc[0]), each.iloc[1])
                print(sql_str)
                query_data(sql_str)
        except Exception as e:
            print('错误', e)


file_name='jp_books-gurupa-us-subtier_browse_tree_guide._TTH_.xls'
increase_data(file_name)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

weixin_43351935

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值