# -*- coding: UTF-8 -*-
"""
-------------------------------------------------------------------------------
# @name: PostgreSqlTableToCSV.py
# @purpose: Exports data from a query of a database postgres
to a CSV file
# @created: 18/05/2012
#-------------------------------------------------------------------------------
"""
import psycopg2
def PostgreSqlTableToCSV(dsn, qry, filecsv, separator=',', quoteStr='"%s"'):
resp = False
con = psycopg2.connect(dsn)
cur = con.cursor()
try:
cur.execute(qry)
closeFile = False
if not hasattr(filecsv, 'write'):
closeFile = True
filecsv = open(filecsv,'w')
filecsv.write(
separator.join([quoteStr % inf[0] for inf in cur.description])
)
for item in cur.fetchall():
filecsv.write('\n'+
separator.join([quoteStr % str(value) for value in item])
)
resp = True
finally:
cur.close()
con.close()
if hasattr(filecsv, 'close') and closeFile:
filecsv.close()
return resp
def example():
#exemplo 1
dsn = "user=postgres password=postgres dbname=cr host=localhost"
print PostgreSqlTableToCSV(
dsn,
'SELECT * FROM cr_cid_cidade',
'c:/tmp/cr_cid_cidade_1.csv',
)
#exemplo 2
dsn = "user=postgres password=postgres dbname=cr host=localhost"
arq = open('c:/tmp/cr_cid_cidade_2.csv','w')
print PostgreSqlTableToCSV(
dsn,
'SELECT * FROM cr_cid_cidade',
arq,
)
arq.close()
if __name__ == '__main__':
example()