单线程脚本

导入文件的行数

# wc -l /data/logs/testlog/20120219/testlog1/*
 1510503 total

  1. # -*- coding: utf-8 -*-
  2. #!/usr/bin/env python
  3. #create database pythondata
  4. #create table log (logline varchar(500));
  5. #grant all on pythondata.* to 'pyuser'@'localhost' identified by "pypasswd";
  6. import MySQLdb
  7. import os
  8. import time
  9. def writeLinestoDb(sql,content):
  10. conn=MySQLdb.connect(host="localhost",user="pyuser",passwd="pypasswd",db="pythondata")
  11. cur =conn.cursor()
  12. cur.executemany(sql,content)
  13. cur.close()
  14. conn.commit()
  15. conn.close()
  16. def readLinestoList(path):
  17. alllines=[]
  18. for file in os.listdir(path):
  19. files=os.path.join(path,file)
  20. for line in open(files):
  21. alllines.append(line)
  22. return alllines
  23. def main():
  24. insertsql ="INSERT INTO log(logline) VALUES(%s)"
  25. alllines=readLinestoList('/data/logs/testlog/20120219/testlog1')
  26. for line in alllines:
  27. content=line.strip()
  28. print content
  29. writeLinestoDb(insertsql,content)
  30. time.sleep(10)
  31. if __name__=="__main__":
  32. print('starting at:',time.ctime())
  33. main()
  34. print('ending at:',time.ctime())
('starting at:', 'Tue Mar 27 11:09:20 2012')
('ending at:', 'Tue Mar 27 11:13:20 2012')
耗时4分钟
mysql> select count(*) from log ;
+----------+
| count(*) |
+----------+
| 1510551 |
+----------+

多线程脚本

  1. # -*- coding: utf-8 -*-
  2. #!/usr/bin/env python
  3. import MySQLdb
  4. import os
  5. from time import ctime
  6. from threading import Thread
  7. from Queue import Queue
  8. in_num_thread=10
  9. out_num_thread=10
  10. in_queue=Queue()
  11. out_queue=Queue()
  12. def listDir(path):
  13. for filename in os.listdir(path):
  14. in_queue.put(os.path.join(path,filename))
  15. def readFile(iq,in_queue):
  16. filelines=[]
  17. while True:
  18. file=in_queue.get()
  19. for line in open(file):
  20. filelines.append(line)
  21. out_queue.put(filelines)
  22. in_queue.task_done()
  23. def writeLinestoDb(oq,out_queue):
  24. sql=insertsql ="INSERT INTO log(logline) VALUES(%s)"
  25. while True:
  26. content=out_queue.get()
  27. conn=MySQLdb.connect(host="localhost",user="pyuser",passwd="pypasswd",db="pythondata")
  28. cur =conn.cursor()
  29. cur.executemany(sql,content)
  30. cur.close()
  31. conn.commit()
  32. conn.close()
  33. out_queue.task_done()
  34. def main():
  35. listDir('/data/logs/testlog/20120219/testlog1')
  36. for iq in range(in_num_thread):
  37. worker=Thread(target=readFile,args(iq,in_queue))
  38. worker.setDaemon(True)
  39. worker.start()
  40. print "Readfile Main Thread Waiting at",ctime()
  41. in_queue.join()
  42. print "Readfile Done at,",ctime()
  43. for oq in range(out_num_thread):
  44. worker=Thread(target=writeLinestoDb,args(oq,out_queue))
  45. worker.setDaemon(True)
  46. worker.start()
  47. print "Insert into mysql Main Thread at",ctime()
  48. out_queue.join()
  49. print "Insert into mysql at,",ctime()
  50. if __name__=="__main__":
  51. print('starting at:',time.ctime())
  52. main()
  53. print('ending at:',time.ctime())
  1. 数据库位于本机
  2. ('starting at:', 'Tue Mar 27 10:57:01 2012')
    Readfile Main Thread Waiting at Tue Mar 27 10:57:01 2012
    Readfile Done at, Tue Mar 27 10:57:04 2012
    Insert into mysql Main Thread at Tue Mar 27 10:57:04 2012
    Insert into mysql at, Tue Mar 27 11:03:34 2012
    ('ending at:', 'Tue Mar 27 11:03:34 2012')
    mysql> select count(*) from log ;
    +----------+
    | count(*) |
    +----------+
    | 3676015 |
    +----------+
  3. 两次个数据不一致,多线的导入有问题
服务器配置4G8核,mysql本地 两个脚本在同一台机器上运行
多线程脚本改进
  1. #!/usr/bin/env python
  2. #create table log ( logline varchar(300));
  3. #grant all on pythondata.* to 'pyuser'@'localhost' identified by "pypasswd"
  4. import MySQLdb
  5. import os
  6. import sys
  7. from time import ctime
  8. from threading import Thread
  9. from Queue import Queue
  10. num_thread=10
  11. queue=Queue()
  12. def listDir(path):
  13. file_list=[]
  14. for filename in os.listdir(path):
  15. file_list.append(os.path.join(path,filename))
  16. return file_list
  17. def readFile(file):
  18. alllines=[]
  19. for line in open(file):
  20. alllines.append(line)
  21. return alllines
  22. def writeLinestoDb(q,queue):
  23. sql=insertsql ="INSERT INTO log(logline) VALUES(%s)"
  24. while True:
  25. content=queue.get()
  26. conn=MySQLdb.connect(host="localhost",user="pyuser",passwd="pypasswd",db="pythondata")
  27. cur =conn.cursor()
  28. cur.executemany(sql,content)
  29. cur.close()
  30. conn.commit()
  31. conn.close()
  32. queue.task_done()
  33. def main():
  34. print "Readfile Start at,",ctime()
  35. for file in listDir('/data/logs/testlog/20120219/testlog1'):
  36. queue.put(readFile(file))
  37. print "Readfile Done at,",ctime()
  38. for q in range(num_thread):
  39. worker=Thread(target=writeLinestoDb,args=(q,queue))
  40. worker.setDaemon(True)
  41. worker.start()
  42. print "Insert into mysql Main Thread at",ctime()
  43. queue.join()
  44. print "Insert into mysql at,",ctime()
  45. if __name__=="__main__":
  46. print('starting at:',ctime())
  47. main()
  48. print('ending at:',ctime())

结果

('starting at:', 'Tue Mar 27 14:32:05 2012')
Readfile Start at, Tue Mar 27 14:32:05 2012
Readfile Done at, Tue Mar 27 14:32:07 2012
Insert into mysql Main Thread at Tue Mar 27 14:32:08 2012
Insert into mysql at, Tue Mar 27 14:34:31 2012
('ending at:', 'Tue Mar 27 14:34:31 2012')
mysql> select count(*) from log;
+----------+
| count(*) |
+----------+
| 1510551 |
+----------+

读用了2秒中,插入使用2分23秒

第一个多线程脚本错误的原因是传入队列的数据问题。 还有一个问题,读的文件超过物理内存和虚拟内存的总量,会造成内存溢出程序挂掉,解决办法每次读取指定行

Python实战(6)单线程和多线程导入mysql数据对比测试的更多相关文章

  1. Sqoop导入mysql数据到Hbase

    sqoop import --driver com.mysql.jdbc.Driver --connect "jdbc:mysql://11.143.18.29:3306/db_1" ...

  2. solr7.4创建core,导入MySQL数据,中文分词

    #solr版本:7.4.0 一.新建Core 进入安装目录下得server/solr/,创建一个文件夹,如:new_core 拷贝server/solr/configsets/_default/con ...

  3. 【实战】使用 Kettle 工具将 mysql 数据增量导入到 MongoDB 中

    最近有一个将 mysql 数据导入到 MongoDB 中的需求,打算使用 Kettle 工具实现.本文章记录了数据导入从0到1的过程,最终实现了每秒钟快速导入约 1200 条数据.一起来看吧~ 一.K ...

  4. 如何导出和导入mysql数据(数据迁移)

    . 导出数据库数据 mysqldump -uroot -p dp_db > dumpout.sql 其中 root是账户名 dp_db是需要导出的数据库名称 dumpout.sql存储导出的数据 ...

  5. HeidiSQL工具导出导入MySQL数据

    有时候,为了数据方便导出导入SQL,我们可以借助一定的工具,方便我们队数据库的移植,可以达到事半功倍的效果.在这里,就给大家简单的介绍一款能方便导出或者导入MySQL的数据. ①首先,选择你要导出的数 ...

  6. excel导入mysql数据

    excel加载mysql数据 1.第一步,选择从mysql导入数据 2.单击会出现弹框: 3.可能有的同学的,这里缺少插件,例如: 4.去下载 这个 插件安装即可.https://dev.mysql. ...

  7. 【Python实战】模块和包导入详解(import)

    1.模块(module) 1.1 模块定义 通常模块为一个.py文件,其他可作为module的文件类型还有".pyo".".pyc".".pyd&qu ...

  8. python将Excel文件内容导入Mysql数据

    为了方便起见,将所有字段类型设置为str,理解mysql的语法这个玩意贼简单 # _*_ coding:utf-8 _*_import pandas as pd #先装个pandas ,pip ins ...

  9. 命令行导入mysql数据

    找到mysql安装目录(bin) 进入mysql mysql -u root -p 123 选中数据库 use 数据库名 导入sql  source sql数据库路径

随机推荐

  1. L1-028. 判断素数

    本题的目标很简单,就是判断一个给定的正整数是否素数. 输入格式: 输入在第一行给出一个正整数N(<=10),随后N行,每行给出一个小于231的需要判断的正整数. 输出格式: 对每个需要判断的正整 ...

  2. shell 中变获取值及运算的几种方法

    num=$(tail ./image/1.txt -n 1) num=$(($num+1))

  3. 基于NEO的私链(Private Blockchain)

    1.准备工作 1.NEO-GUI 2.NEO-CLI 3..NET Core Runtime (不能是2.x版本,官方建议是1.12,实际上我用1.14也是没有问题的) 4.四台windows操作系统 ...

  4. 关于Q-LEARNING的优化

    Q-LEARNING 最后得到的一个图寻路最佳路径:---直接转化为图关于多顶点深度遍历热度传递 V(level+1) = 0.8 * Max(Vi(level))   这个方法可以在O时间收敛 原方 ...

  5. Redis分布式锁实现

    redis分布式锁的一个简单直接的实现方法就是用 SET NX 命令设置一个设定了存活周期 TTL 的 Key 来获取锁,通过删除 Key 来释放锁,通过存活周期来避免死锁.不过这个方法存在单点故障风 ...

  6. php腾讯面试题(转)

    一.PHP开发部分 1.合并两个数组有几种方式,试比较它们的异同 答:1.array_merge() 2.’+’ 3.array_merge_recursive array_merge 简单的合并数组 ...

  7. tarfile — Read and write tar archive files

    参考: https://docs.python.org/2/library/tarfile.html http://www.jianshu.com/p/bbad16822eab #解压文件tarfil ...

  8. Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.

    Struts Problem Report Struts has detected an unhandled exception: Messages: Write operations are not ...

  9. Unity查找物体的子物体、孙物体

    Unity查找物体下的所有物体 本文提供全流程,中文翻译. Chinar 坚持将简单的生活方式,带给世人!(拥有更好的阅读体验 -- 高分辨率用户请根据需求调整网页缩放比例) Chinar -- 心分 ...

  10. QT学习相关

    1. vs2012的编译器对execution_character_set("utf-8")无反应的bug在vs2013中解决 2. 安装上vs2013后,重装的qt插件,发现不能 ...