abcd
efgh
ijkl
mnop
按13个字符取内容
root_path = os.path.abspath('./') + os.sep
f = open(root_path + 'file/pass.txt', 'r')
f.seek(0)
line = f.read(13) #从文件中读取一段内容
输出如下:(回车[\n]占一个字符)
abcd
efgh
ijk
转换为数组后
L = ['abcd', 'efgh', 'ijk']
此时插入数据库内容为
['abcd', 'efgh']
将最后一条数据缓存 t = L.pop()
下一次循环得到数组为
L = ['l', 'mnop']
此时将第一条数据和缓存的数据合并
L[0] = t + L[0]
并缓存数组最后一条数据
二 插入数据
插入数据,使用批量插入
最开始的时候我拼好sql语句如:INSERT INTO XX(`a`) VALUES(1),(2),(3)...
然后调用mysql-python的方法
conn = mysql.connector.connect(host='127.0.0.1', database='xxx', user='xxx', password='xxx')
conn.cursor().execute(sql)
结果执行了大概2万多就报Lost connection to MySQL server错误了。后来我看mysql-python里面的代码原来批量插入数据有封装好的方法是
conn.cursor().execute(sql)
data = [
('Jane','555-001'),
('Joe', '555-001'),
('John', '555-003')
]
stmt = "INSERT INTO employees (name, phone) VALUES (%s,%s)"
cursor.executemany(stmt, data)
注意以上两点后,上代码:
#encoding:utf-8
'''
Created on 2013-1-27
@author: JinHanJiang
'''
'''
create table
CREATE TABLE `Passwords` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'id主键',
`pass` varchar(64) NOT NULL COMMENT '密码',
`md5` varchar(32) DEFAULT NULL COMMENT '32位md5值',
PRIMARY KEY (`id`),
UNIQUE KEY `pass` (`pass`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='密码'
'''
import os
import re
import time
from datetime import datetime
import hashlib
import mysql.connector
import random
root_path = os.path.abspath('./') + os.sep
f = open(root_path + 'file/f1.txt', 'r')
fields = ['pass', 'md5']
def writeDB(params):
try:
fields = '(`' + '`, `'.join(params['fields']) + '`)'
stmt = "INSERT IGNORE INTO Passwords"+fields+" VALUES (%s,%s)"
conn = mysql.connector.connect(host='127.0.0.1', database='password', user='root', password='admin')
conn.cursor().executemany(stmt, params['datas'])
conn.cursor().close()
conn.close()
except Exception as e:
print e
pos = 0
buff = 1024 * 1024
last = ''
dstart = datetime.now()
print "Program Start At: " + dstart.strftime('%Y-%m-%d %H:%M:%S')
while 1:
f.seek(pos)
line = f.read(buff) #从文件中读取一段内容
datas = []
if not line:
if '' is not last:
data = (last, hashlib.md5(last).hexdigest().upper())
datas.append(data)
params = {'fields': fields, 'datas': datas}
writeDB(params)
break; #如果内容为空跳出循环
pos += buff #计算取下一段内容长度
buff = pos
lines = re.split("\n", line) #以回车(\n)分隔内容到数组中
lines[0] = str(last) + str(lines[0])
last = lines.pop() #将数组最后一条数据剔除,并存到last变量中,到下次循环再处理
for lin in lines:
lin = lin.rstrip() #去除内容末尾的回车字符
if not lin:
continue
data = (lin, hashlib.md5(lin).hexdigest().upper())
datas.append(data) #封装内容
if len(datas) > 0:
params = {'fields': fields, 'datas': datas}
writeDB(params)
time.sleep(random.random()) #让Cpu随机休息0 <= n < 1.0 s
f.close()
dend = datetime.now()
print "Program End At:%s Time span %s"%(dend.strftime('%Y-%m-%d %H:%M:%S'), dend - dstart);
下载次数: 56
分享到:
2013-01-27 20:49
浏览 9543
论坛回复 / 浏览 (6 / 20841)
评论