Python 如何在psycopg2中为并发连接测试建立20个连接
我想做一些并发连接测试,并希望通过psycopg2适配器建立50个到数据库的并发连接。我该怎么办 我应该使用psycopg2.pool建立并发连接还是使用线程Python 如何在psycopg2中为并发连接测试建立20个连接,python,sql,database,postgresql,psycopg2,Python,Sql,Database,Postgresql,Psycopg2,我想做一些并发连接测试,并希望通过psycopg2适配器建立50个到数据库的并发连接。我该怎么办 我应该使用psycopg2.pool建立并发连接还是使用线程 a = psycopg2.pool.SimpleConnectionPool(1,50,database='test') @contextmanager def getcursor(): con = a.getconn() con.autocommit = True try: yield con.
a = psycopg2.pool.SimpleConnectionPool(1,50,database='test')
@contextmanager
def getcursor():
con = a.getconn()
con.autocommit = True
try:
yield con.cursor()
finally:
a.putconn(con)
for i in xrange(50):
with getcursor() as cur:
cur.execute("select * from test")
或者我应该每次直接创建连接,例如:
for i in xrange(50):
con = psycopg2.connect(database='test',user='test', host='localhost', password='test')
cur = con.cursor()
cur.execute("select * from test")
con.close()
还是应该每次都创建新线程?提前感谢我使用数组存储连接并进行异步查询谢谢,Jasen,我还是有点困惑。你能给我更多的细节吗?如果可能的话,给我一些示例代码?提前感谢(假设
psycopg2
在阻塞调用期间释放GIL),这两种方法都非常简单。在我看来,这两种方法都不是并发的。他们不只是串行地使用连接吗?我认为测试应该尽可能接近你预期的实际使用。