(1小记录)python写向数据库导入一个有100万行的csv文件,速度终于快了
- 一开始用load infile直接整个文件导入,结果Python报错:MemoryError
一开始用load infile直接整个文件导入,结果Python报错:MemoryError
导入语句:
load_sql = “”" LOAD DATA lOCAL INFILE ‘{}’ INTO TABLE {} FIELDS TERMINATED by ‘,’
optionally enclosed by ‘"’ escaped by ‘"’ lines terminated by “rn”;;""".format
(tempCSVDir, tableName)
解决方案:
1、把文件分成1万行进行100次导入,写入临时文件,再读入,结果花了17分钟!
2、尝试着一次读多些行,发现其实导入10万行速度也是快的,花了95秒
3、导入30万行速度也是花了95秒
4、自己写了一个函数进行文件分割:
fileDir:文件完整路径
ig:忽略文件几行
row:导入文件几行
timenum:第几次调用
allNrows:全部导入几行了
fileName:文件名字
tempCSVPath:存放临时csv文件的位置,结尾是带/的
(1)中间try…except…是因为文件编码太多种了…
(2)一开始try…except…是因为文件如果截取到全部空行的话会报错,这时候我就判断为截取文件完毕
(3)load data infile 中间加了local 是因为我导入的文件是在共享盘上(映射到本地)的文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54// An highlighted block def read_part_file(fileDir,ig,row,timenum,allNrows,fileName,tempCSVPath): try: if ".csv" in fileDir: try: fileData = pd.read_csv(fileDir,skiprows=ig, nrows=row, low_memory=False, encoding='utf_8_sig') except: fileData = pd.read_csv(fileDir,skiprows=ig, nrows=row, low_memory=False, encoding='gb2312') elif ".xls" in fileDir: fileData = pd.read_excel(fileDir,skiprows=ig, nrows=row) allNrows = allNrows + fileData.iloc[:, 0].size+1 except: print("第%d次调用,空" %timenum) print("文件分片结束") print("一共导入%d行" %allNrows) return print("第%d次调用" % timenum) print("忽略%d行" % ig) print("导入%d行" % row) ig = ig + row + 1 nrows = fileData.iloc[:, 0].size + 1 print("本次导入"+str(nrows)+"行") print(fileData) timenum = timenum+1 strTimeNum = str(timenum) tempCSVDir = tempCSVPath + strTimeNum + fileName fileData.to_csv(tempCSVDir, index=False, encoding='utf_8_sig') # 连接数据库 host = "localhost" user = "root" password = "111" db = "mydb" # 打开数据库连接 db = pymysql.connect(host, user, password, db, charset='utf8', local_infile=1) # 使用cursor()方法获取操作游标 cursor = db.cursor() print("Connected to DB:{}".format(host)) # 导入csv文件 load_sql = """ LOAD DATA lOCAL INFILE '{}' INTO TABLE {} FIELDS TERMINATED by ',' optionally enclosed by '"' escaped by '"' lines terminated by "rn";;""".format (tempCSVDir, tableName) try: cursor.execute(load_sql) except Exception as e: print("Error:{}".format(str(e))) sys.exit(1) print(str(tempCSVDir) + '成功!') cursor.connection.commit() # 执行commit操作,插入语句才能生效[每次总是差了这么两句] db.close() return read_part_file(fileDir, ig, row, timenum, allNrows, fileName,tempCSVPath)
2022年3月12日来更新加快数据写入数据库的方法啦~
1
2
3
4
5#设置写入类型,默认是用CLOB类型写入,内置的类型转换很慢,小量数据则无影响 dtyp = {c: types.VARCHAR(fileData[c].str.len().max()) for c in fileData.columns[fileData.dtypes == 'object'].tolist()} df.to_sql(tableName, con=engine_a, index=False, if_exists='append', index_label=None,dtype=dtyp)
最后
以上就是结实钻石最近收集整理的关于python写向数据库导入一个有100万行的csv文件,提高速度,还是要95秒一开始用load infile直接整个文件导入,结果Python报错:MemoryError的全部内容,更多相关python写向数据库导入一个有100万行的csv文件,提高速度,还是要95秒一开始用load内容请搜索靠谱客的其他文章。
发表评论 取消回复