1啰劲、支持分批導(dǎo)入(可配置)
2、批量導(dǎo)入降低數(shù)據(jù)庫操作
3鲸睛、批量數(shù)據(jù)錯誤會自動重新生成導(dǎo)入數(shù)據(jù)最終只剩下錯誤數(shù)據(jù)昨寞,保證數(shù)據(jù)正確率和打入率最大化
CODE:
? ??
#!/usr/bin/python3
import xlrd
import pymysql
import os
import json
dataHost = ""
dataUser = ""
dataPwd? = ""
dataName = "test"
#錯誤數(shù)據(jù)文件存儲位置
errorFile = "./errorFile.json"
#導(dǎo)入數(shù)據(jù)源
excelFile = "./jb.xlsx"
#一次允許灌入數(shù)據(jù)庫數(shù)據(jù)的條數(shù)
onceInsertNum = 5
#一次允許灌入數(shù)據(jù)庫的原始數(shù)據(jù)
dataList = []
#一次允許最多讀入EXCEL數(shù)據(jù)條數(shù)
onceReadExcelNum = 10
# 打開數(shù)據(jù)庫連接
print("連接數(shù)據(jù)庫.......")
db = pymysql.connect(dataHost,dataUser,dataPwd,dataName)
print("數(shù)據(jù)庫連接成功!")
'''
? ? 將數(shù)據(jù)灌入數(shù)據(jù)庫
'''
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ù)庫.....")
? ? ? ? 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ā)生錯誤時回滾
? ? ? ? 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ù)庫
? ? db.close()