PY3 批量導(dǎo)入EXCEL到數(shù)據(jù)庫(kù)腳本模板

1、支持分批導(dǎo)入(可配置)

2、批量導(dǎo)入降低數(shù)據(jù)庫(kù)操作

3、批量數(shù)據(jù)錯(cuò)誤會(huì)自動(dòng)重新生成導(dǎo)入數(shù)據(jù)最終只剩下錯(cuò)誤數(shù)據(jù),保證數(shù)據(jù)正確率和打入率最大化

CODE:

? ??


#!/usr/bin/python3

import xlrd

import pymysql

import os

import json

dataHost = ""

dataUser = ""

dataPwd? = ""

dataName = "test"

#錯(cuò)誤數(shù)據(jù)文件存儲(chǔ)位置

errorFile = "./errorFile.json"

#導(dǎo)入數(shù)據(jù)源

excelFile = "./jb.xlsx"

#一次允許灌入數(shù)據(jù)庫(kù)數(shù)據(jù)的條數(shù)

onceInsertNum = 5

#一次允許灌入數(shù)據(jù)庫(kù)的原始數(shù)據(jù)

dataList = []

#一次允許最多讀入EXCEL數(shù)據(jù)條數(shù)

onceReadExcelNum = 10

# 打開數(shù)據(jù)庫(kù)連接

print("連接數(shù)據(jù)庫(kù).......")

db = pymysql.connect(dataHost,dataUser,dataPwd,dataName)

print("數(shù)據(jù)庫(kù)連接成功!")

'''

? ? 將數(shù)據(jù)灌入數(shù)據(jù)庫(kù)

'''

def insertDbData(params=[], onceInsertNums=20):

? ? lens = len(params)

? ? if lens < 1:

? ? ? ? print("無插入數(shù)據(jù)")

? ? ? ? return

? ? if int(lens / onceInsertNums) * onceInsertNums == lens:

? ? ? ? tempLens = int(lens / onceInsertNums)

? ? else:

? ? ? ? tempLens = int((lens / onceInsertNums) + 1)

? ? for i in range(tempLens):

? ? ? ? dataList.clear()

? ? ? ? # SQL 插入語句


? ? ? ? jnums = onceInsertNums

? ? ? ? if i == tempLens - 1:

? ? ? ? ? ? if tempLens * onceInsertNums != lens:

? ? ? ? ? ? ? ? jnums = lens % onceInsertNums


? ? ? ? for j in range(i*onceInsertNums, i*onceInsertNums+jnums):

? ? ? ? ? ? dataList.append(params[j])

? ? ? ? sqlLists = getSqlLists(dataList)

? ? ? ? insertData(sqlLists)

def getSqlLists(params=[]):

? ? sql = "INSERT INTO test(bh,ptdjr,gcrxm,khjl,jsyxm,bjscjc,cph,dgjc,bz) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s) "

? ? lists = []

? ? # for i in params:

? ? #? ? sql += str(tuple(i)) + ","

? ? # sql = sql.strip(',')

? ? # sql += ";"

? ? for i in params:

? ? ? ? lists.append(tuple(i))

? ? return [[sql, lists]]

def insertData(sqlLists):

? ? # 使用cursor()方法獲取操作游標(biāo)

? ? cursor = db.cursor()

? ? try:

? ? ? ? print("開始操作數(shù)據(jù)庫(kù).....")

? ? ? ? for sql in sqlLists:

? ? ? ? ? ? print(sql[0])

? ? ? ? ? ? print(sql[1])

? ? ? ? ? ? # 執(zhí)行sql語句

? ? ? ? ? ? cursor.executemany(sql[0], sql[1])

? ? ? ? db.commit()

? ? ? ? print("提交數(shù)據(jù)成功!")

? ? ? ? # results = cursor.fetchall()

? ? ? ? # print(results)

? ? except:

? ? ? ? # 發(fā)生錯(cuò)誤時(shí)回滾

? ? ? ? db.rollback()

? ? ? ? print("插入失敗=>數(shù)據(jù)回滾中")

? ? ? ? writeFiles(errorFile ,dataList)

#獲取EXCEL數(shù)據(jù)

def redDataFormExcel(fileName):

? ? dontReadRows = [0,1]

? ? dontReadCols = []

? ? # 打開execl

? ? workbook = xlrd.open_workbook(fileName)

? ? # 根據(jù)sheet索引或者名稱獲取sheet內(nèi)容

? ? Data_sheet = workbook.sheets()[0]? # 通過索引獲取

? ? # Data_sheet = workbook.sheet_by_index(0)? # 通過索引獲取

? ? # Data_sheet = workbook.sheet_by_name(u'Sheet2')? # 通過名稱獲取

? ? rowNum = Data_sheet.nrows? # sheet行數(shù)

? ? colNum = Data_sheet.ncols? # sheet列數(shù)

? ? print("行數(shù):" + str(rowNum))

? ? print("列數(shù):" + str(colNum))

? ? if int(rowNum / onceReadExcelNum) * onceReadExcelNum == rowNum:

? ? ? ? tempRowNum = int(rowNum / onceReadExcelNum)

? ? else:

? ? ? ? tempRowNum = int(rowNum / onceReadExcelNum) + 1

? ? iCnt = 0

? ? lists = []

? ? rowlist = []

? ? while iCnt < tempRowNum:

? ? ? ? print("-----------------------------開始讀取數(shù)據(jù)---------------------------")

? ? ? ? getRowNum = onceReadExcelNum

? ? ? ? if iCnt == tempRowNum - 1:

? ? ? ? ? ? if tempRowNum * onceReadExcelNum != rowNum:

? ? ? ? ? ? ? ? getRowNum = rowNum % onceReadExcelNum

? ? ? ? lists.clear()

? ? ? ? rowListIndex = list(range(iCnt * onceReadExcelNum, iCnt * onceReadExcelNum + getRowNum))

? ? ? ? colListIndex = list(range(colNum))

? ? ? ? for i in dontReadCols:

? ? ? ? ? ? if i in colListIndex:

? ? ? ? ? ? ? ? colListIndex.remove(i)

? ? ? ? for i in dontReadRows:

? ? ? ? ? ? if i in rowListIndex:

? ? ? ? ? ? ? ? rowListIndex.remove(i)

? ? ? ? for i in rowListIndex:

? ? ? ? ? ? rowlist = []

? ? ? ? ? ? for j in colListIndex:

? ? ? ? ? ? ? ? rowlist.append(Data_sheet.cell_value(i, j))

? ? ? ? ? ? lists.append(rowlist)

? ? ? ? print("--------------------------------讀取完成-----------------------------")

? ? ? ? insertDbData(lists, onceInsertNum)

? ? ? ? iCnt += 1

? ? # 輸出所有單元格的內(nèi)容

? ? # print(list)

? ? # os._exit(0)

? ? # for i in lists:

? ? #? ? for j in i:

? ? #? ? ? ? print(j, '\t\t', end="")

? ? #? ? print()

? ? # 獲取整行和整列的值(列表)

? ? # rows = Data_sheet.row_values(0)? # 獲取第一行內(nèi)容

? ? # cols = Data_sheet.col_values(1)? # 獲取第二列內(nèi)容

? ? # print (rows)

? ? # print (cols)

? ? # os._exit(0)

? ? # 獲取單元格內(nèi)容

? ? # cell_A1 = Data_sheet.cell(0, 0).value

? ? # cell_B1 = Data_sheet.row(0)[1].value? # 使用行索引

? ? # cell_C1 = Data_sheet.cell(0, 2).value

? ? # cell_D2 = Data_sheet.col(3)[1].value? # 使用列索引

? ? # print(cell_A1, cell_B1, cell_C1, cell_D2)

? ? # os._exit(0);

? ? # 獲取單元格內(nèi)容的數(shù)據(jù)類型

? ? # ctype:0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error

? ? # print('cell(0,0)數(shù)據(jù)類型:', Data_sheet.cell(0, 2).ctype)

? ? # print('cell(1,0)數(shù)據(jù)類型:', Data_sheet.cell(1, 0).ctype)

? ? # print('cell(5,1)數(shù)據(jù)類型:', Data_sheet.cell(5, 1).ctype)

? ? # print('cell(1,2)數(shù)據(jù)類型:', Data_sheet.cell(1, 2).ctype)

? ? # os._exit(0)

? ? # 獲取單元格內(nèi)容為日期的數(shù)據(jù)

? ? # date_value = xlrd.xldate_as_tuple(Data_sheet.cell_value(1,0),workbook.datemode)

? ? # print(type(date_value), date_value)

? ? # print('%d:%d:%d' % (date_value[0:3]))

#寫入文件

def writeFiles(fileName, data):

? ? file = open(fileName, "a+", encoding="utf8")

? ? for i in data:

? ? ? ? temp = i

? ? ? ? if isinstance(i, list):

? ? ? ? ? ? temp = json.dumps(i,ensure_ascii=False)

? ? ? ? file.write(temp+"\n")

? ? file.close()

? ? print("失敗數(shù)據(jù)寫入文件成功")


def readErrorFile():

? ? if not os.path.exists(errorFile):

? ? ? ? return

? ? booles = False

? ? tempIcnt = onceInsertNum

? ? while True:

? ? ? ? if not booles:

? ? ? ? ? ? file = open(errorFile, 'r+', encoding='utf8')

? ? ? ? ? ? lines = file.readlines()

? ? ? ? ? ? file.seek(0)

? ? ? ? ? ? file.truncate()

? ? ? ? ? ? file.close()

? ? ? ? ? ? tempDataList = []

? ? ? ? ? ? for i in lines:

? ? ? ? ? ? ? ? tempDataList.append(json.loads(i.strip()))

? ? ? ? ? ? iCnt = int(tempIcnt / 2)

? ? ? ? ? ? tempIcnt = iCnt

? ? ? ? ? ? if iCnt == 0:

? ? ? ? ? ? ? ? iCnt = 1

? ? ? ? ? ? if iCnt == 1:

? ? ? ? ? ? ? ? booles = True

? ? ? ? ? ? insertDbData(tempDataList, iCnt)

? ? ? ? else:

? ? ? ? ? ? break

if __name__ == '__main__':

? ? redDataFormExcel(excelFile)

? ? readErrorFile()

? ? #關(guān)閉數(shù)據(jù)庫(kù)

? ? db.close()

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • pyspark.sql模塊 模塊上下文 Spark SQL和DataFrames的重要類: pyspark.sql...
    mpro閱讀 9,920評(píng)論 0 13
  • 本文以Loadrunner的Java_Vuser腳本為例,來做一個(gè)簡(jiǎn)化版的自動(dòng)化測(cè)試框架(以excel作為數(shù)據(jù)驅(qū)動(dòng)...
    smooth00閱讀 595評(píng)論 0 0
  • 1.13感恩日記 感恩今天是周末,我可以去街上采購(gòu)好多孩子們愛吃的食材,給他們做可口的飯菜。 感恩兒子乖巧懂事,我...
    種子高手閱讀 265評(píng)論 0 0
  • 今天拿出早已買好的吳軍老師的書《見識(shí)》,買下來很長(zhǎng)一段時(shí)間了,可是卻一直擱置沒有打開。想著最近自己實(shí)在寫不...
    開往春天的綠蘿閱讀 209評(píng)論 1 1
  • 1、實(shí)際預(yù)測(cè)過程中,一般都把未戍土當(dāng)火論、辰丑土當(dāng)水論就行了。 2、雖然看起來辰戍丑未很復(fù)雜,實(shí)際預(yù)測(cè)時(shí),只需明白...
    Forin_閱讀 930評(píng)論 0 0

友情鏈接更多精彩內(nèi)容