Python多进程并发写入PostgreSQL数据表
1、前言前两天开了两个进程,把Python抓回的数据链接并发写入Mysql中,结果显示出错。后来一查才知道需要自己设置锁,好生麻烦。这时PostgreSQL进入了我的视野,因为这家伙原生就是多进程的,但它是否支持多进程并发写入呢,还需要实际实验一下才知道。
2、安装PostgreSQL
第一步,进入官网:http://www.postgresql.org/,点击Download
第二步,选择操作系统对应的版本
第三步,我选择的Windows平台,因此下载说明该套件还包括视窗管理工具pgAdmin III。
继续下载,我选择的是64位,然后安装。接下来就是用pgAdmin创建数据库和表,老一套了,在此省略不表。
3、编写Python脚本
首先,需要安装Psycopg,这是Python访问PostgreSQL的链接库。官网上说windows版本需要下载安装包,其实也有pip的安装方式:
[*]pip install psycopg2
遗憾的是pip方式出现了问题,不知道是不是阅兵时的网络问题。
所以,我选择下载安装包:
4、测试结果
写入测试结果显示:可以实现两个进程对同一数据表的并发写入
但是,我也将同样的代码跑了一下Mysql,发现并发的很好。。。郁闷
所以,现在要更多的测试
[*]# -*- coding: utf-8 -*-
[*]import threading,time
[*]#import psycopg2
[*]import MySQLdb
[*]import string
[*]
[*]def multiGet(who):
[*] start = time.clock()
[*] #conn = psycopg2.connect(user='postgres',password='123456',database='links',host='localhost',port="5432")
[*] conn = MySQLdb.connect(host='localhost',user='root',passwd='',db='rmrb')
[*] cursor = conn.cursor()
[*] for i in range(1000):
[*] sql = "INSERT INTO delta (ID,WHO) VALUES (NULL, '" + who + "' );"
[*] cursor.execute(sql)
[*] conn.commit()
[*] cursor.close()
[*] conn.close()
[*] end = time.clock()
[*] print who + " processing time is: %f s" % (end - start)
[*]
[*]task1 = threading.Thread(target = multiGet, args = ("a"))
[*]task1.start()
[*]task2 = threading.Thread(target = multiGet, args = ("b"))
[*]task2.start()
这时,出现了问题,主要是关键字段ID不能为空。所以,改善一下代码:
[*]# -*- coding: utf-8 -*-
[*]import threading,time
[*]#import psycopg2
[*]import MySQLdb
[*]import string
[*]
[*]def multiGet(who):
[*] start = time.clock()
[*] #conn = psycopg2.connect(user='postgres',password='123456',database='links',host='localhost',port="5432")
[*] conn = MySQLdb.connect(host='localhost',user='root',passwd='',db='rmrb')
[*] cursor = conn.cursor()
[*] for i in range(1000):
[*] if who == 'a':
[*] sql = "INSERT INTO delta (ID,WHO) VALUES (" + str(i) + ", '" + who + "' );"
[*] else:
[*] sql = "INSERT INTO delta (ID,WHO) VALUES (" + str(i+1000) + ", '" + who + "' );"
[*] cursor.execute(sql)
[*] conn.commit()
[*] cursor.close()
[*] conn.close()
[*] end = time.clock()
[*] print who + " processing time is: %f s" % (end - start)
[*]
[*]task1 = threading.Thread(target = multiGet, args = ("a"))
[*]task1.start()
[*]task2 = threading.Thread(target = multiGet, args = ("b"))
[*]task2.start()
Mysql的结果如下:
上述结果是最后全部写入的,改成每条都commit呢?结果如下:
[*]b processing time is: 0.161019 sa processing time is: 0.162407 s
但是,这是InnoDB引擎的结果,数据量特大时,这个引擎超级慢。所以设置为MyISAM再试试。
[*]a processing time is: 0.160377 sb processing time is: 0.159764 s
速度加快了,程度的调度其实还是分片,a一片然后b一片。
4、结论
看来Mysql足够,只是需要在关键字段的设置上做好功夫就可以。
页:
[1]