I'm trying to execute 3 different postgresql queries with different table. Each query takes 2 seconds to execute. I was wondering if it's possible to run all 3 queries at the same time so that I can save 4 seconds. I tried using the asynchronous feature of pyscopg2
but it only returns the result of last query. Can anyone point out what I'm doing wrong ?
import select
import psycopg2
import psycopg2.extensions
def wait(conn):
while 1:
state = conn.poll()
if state == psycopg2.extensions.POLL_OK:
break
elif state == psycopg2.extensions.POLL_WRITE:
select.select([], [conn.fileno()], [])
elif state == psycopg2.extensions.POLL_READ:
select.select([conn.fileno()], [], [])
else:
raise psycopg2.OperationalError("poll() returned %s" % state)
aconn = psycopg2.connect(
dbname=pg_name,
user=pg_username,
host=pg_host,
password=pg_password,
async=1)
wait(aconn)
acurs = aconn.cursor()
acurs.execute(
"SELECT 1;"
"SELECT ST_Length(ST_GeomFromText"
"('LINESTRING(743238 2967416,743238 2967450)',4326));"
"SELECT 3;"
)
wait(acurs.connection)
result = acurs.fetchall()
print result
This only prints: "result": [[3]]