数学建模社区-数学中国

标题: Python读取大文件并插入数据库 [打印本页]

作者: 杨利霞    时间: 2021-1-8 17:52
标题: Python读取大文件并插入数据库
Python读取大文件并插入数据库



把几个大的文件的内容读到数据库中。
查看了手册open方法,首先想到了seek()方法,和fread()方法读到一段内容来执行插入。

大概说一下方法吧。

取数据
取一段内容,以回车(\n)分隔内容为数据,批量插入数据库

如要读取文件内容如下:
Python代码  file:///C:\Users\ADMINI~1\AppData\Local\Temp\ksohtml13724\wps1.jpg
1. abcd  
2. efgh  
3. ijkl  
4. mnop  


13个字符取内容
Python代码  file:///C:\Users\ADMINI~1\AppData\Local\Temp\ksohtml13724\wps2.jpg
1. root_path = os.path.abspath('./') + os.sep   
2. f = open(root_path + 'file/pass.txt', 'r')  
3.   
4. f.seek(0)  
5. line = f.read(13) #从文件中读取一段内容  


输出如下:(回车[\n]占一个字符)
Python代码  file:///C:\Users\ADMINI~1\AppData\Local\Temp\ksohtml13724\wps3.jpg
1. abcd  
2. efgh  
3. ijk  


转换为数组后
Python代码  file:///C:\Users\ADMINI~1\AppData\Local\Temp\ksohtml13724\wps4.jpg
1. L = ['abcd', 'efgh', 'ijk']  

此时插入数据库内容为
Python代码  file:///C:\Users\ADMINI~1\AppData\Local\Temp\ksohtml13724\wps5.jpg
1. ['abcd', 'efgh']  

将最后一条数据缓存 t = L.pop()

下一次循环得到数组为
Python代码  file:///C:\Users\ADMINI~1\AppData\Local\Temp\ksohtml13724\wps6.jpg
1. L = ['l', 'mnop']  

此时将第一条数据和缓存的数据合并
Python代码  file:///C:\Users\ADMINI~1\AppData\Local\Temp\ksohtml13724\wps7.jpg
1. L[0] = t + L[0]   

并缓存数组最后一条数据

插入数据

插入数据,使用批量插入
最开始的时候我拼好sql语句如:INSERT INTO XX(`a`) VALUES(1),(2),(3)...

然后调用mysql-python的方法
Python代码  file:///C:\Users\ADMINI~1\AppData\Local\Temp\ksohtml13724\wps8.jpg
1. sql = 'INSERT INTO XX(`a`) VALUES(1),(2),(3)'  
2. conn = mysql.connector.connect(host='127.0.0.1', database='xxx', user='xxx', password='xxx')  
3. conn.cursor().execute(sql)  


结果执行了大概2万多就报Lost connection to MySQL server错误了。后来我看mysql-python里面的代码原来批量插入数据有封装好的方法是
Python代码  file:///C:\Users\ADMINI~1\AppData\Local\Temp\ksohtml13724\wps9.jpg
1. data = [  
2.          ('Jane','555-001'),  
3.          ('Joe', '555-001'),  
4.          ('John', '555-003')  
5.          ]  
6. stmt = "INSERT INTO employees (name, phone) VALUES (%s,%s)"  
7. cursor.executemany(stmt, data)  


注意以上两点后,上代码:
Python代码  file:///C:\Users\ADMINI~1\AppData\Local\Temp\ksohtml13724\wps10.jpg
1. #encoding:utf-8  
2. '''''
3. Created on 2013-1-27
4. @author: JinHanJiang
5. '''  
6.   
7.   
8. '''''
9. create table
10. CREATE TABLE `Passwords` (
11.    `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'id主键',
12.    `pass` varchar(64) NOT NULL COMMENT '密码',
13.    `md5` varchar(32) DEFAULT NULL COMMENT '32位md5值',
14.    PRIMARY KEY (`id`),
15.    UNIQUE KEY `pass` (`pass`)
16.  ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='密码'
17. '''  
18.   
19. import os  
20. import re  
21. import time  
22. from datetime import datetime  
23. import hashlib  
24. import mysql.connector  
25. import random  
26.   
27. root_path = os.path.abspath('./') + os.sep   
28. f = open(root_path + 'file/f1.txt', 'r')  
29. fields = ['pass', 'md5']  
30.   
31.           
32. def writeDB(params):  
33.     conn = cur = None  
34.     try:  
35.         fields = '(`' + '`, `'.join(params['fields']) + '`)'  
36.         stmt = "INSERT IGNORE INTO Passwords"+fields+" VALUES (%s,%s)"  
37.           
38.         conn = mysql.connector.connect(host='127.0.0.1', database='password', user='root', password='admin')  
39.         cur = conn.cursor()  
40.         cur.executemany(stmt, params['datas'])  
41.     except mysql.connector.Error as e:  
42.         print e  
43.     finally:  
44.         if cur:  
45.             cur.close()  
46.         if conn:  
47.             conn.commit() #如果数据库表类型是Innodb记的带个参数  
48.             conn.close()  
49.   
50. pos = 0  
51. step = buff = 1024 * 1024  
52. last = ''  
53.   
54. dstart = datetime.now()  
55. print "Program Start At: " + dstart.strftime('%Y-%m-%d %H:%M:%S')  
56.   
57. while 1:  
58.     f.seek(pos)  
59.     line = f.read(buff) #从文件中读取一段内容  
60.     datas = []  
61.      
62.     if not line:  
63.         if '' is not last:  
64.             data = (last, hashlib.md5(last).hexdigest().upper())  
65.             datas.append(data)  
66.             params = {'fields': fields, 'datas': datas}  
67.             writeDB(params)  
68.         break; #如果内容为空跳出循环  
69.      
70.     pos += step #计算取下一段内容长度  
71.      
72.     lines = re.split("\n", line) #以回车(\n)分隔内容到数组中  
73.      
74.     lines[0] = str(last) + str(lines[0])   
75.     last = lines.pop()  #将数组最后一条数据剔除,并存到last变量中,到下次循环再处理  
76.      
77.     for lin in lines:  
78.         lin = lin.rstrip() #去除内容末尾的回车字符  
79.         if not lin:  
80.             continue  
81.           
82.         data = (lin, hashlib.md5(lin).hexdigest().upper())  
83.         datas.append(data) #封装内容  
84.      
85.     if len(datas) > 0:  
86.         params = {'fields': fields, 'datas': datas}  
87.         writeDB(params)  
88.           
89.     time.sleep(random.random()) #让Cpu随机休息0 <= n < 1.0 s   
90.   
91. f.close()  
92.   
93. dend = datetime.now()  
94. print "Program End At:%s Time span %s"%(dend.strftime('%Y-%m-%d %H:%M:%S'), dend - dstart);  









欢迎光临 数学建模社区-数学中国 (http://www.madio.net/) Powered by Discuz! X2.5