Friday, February 10, 2012

psycopg2 template


#!/usr/bin/python
'''

description here: This is a template how to run PostgreSQL queries from a python script

Params:
    $1 - argv...
'''

import sys
import psycopg2
from datetime import *

if len(sys.argv) <> 3:
    print "Usage:\n %s param1 param2" % sys.argv[0]
    sys.exit(0)

param1=sys.argv[1]
param2=sys.argv[2]

conn_string = "host='localhost' dbname='db' user='user' password='pass'"

query = "select bla bla bla " +str(param1)


def main():
    conn = psycopg2.connect(conn_string)
    curs = conn.cursor()


    curs.execute(query)
    for row in curs:
print "%s" % row

# for update/insert
# conn.commit()
    curs.close()
    conn.close()

    sys.stdout.flush()
    sys.stderr.flush()


if __name__ == "__main__":
    sys.exit(main())