Tech notes

Export query from postgresql to csv

Example from: Stackoverflow

import sys

#set up psycopg2 environment
import psycopg2

#driving_distance module
#note the lack of trailing semi-colon in the query string, as per the Postgres documentation
query = “””
select *
from driving_distance ($$
select
gid as id,
start_id::int4 as source,
end_id::int4 as target,
shape_leng::double precision as cost
from network
$$, %s, %s, %s, %s
)
“””

#make connection between python and postgresql
conn = psycopg2.connect(“dbname = ‘routing_template’ user = ‘postgres’ host = ‘localhost’ password = ‘xxxx'”)
cur = conn.cursor()

outputquery = “COPY ({0}) TO STDOUT WITH CSV HEADER”.format(query)

with open(‘resultsfile’, ‘w’) as f:
cur.copy_expert(outputquery, f)

conn.close()

Comment here