yuanlii / SAND-project

Working documents of SAND project.
0 stars 0 forks source link

Connect to postgres db #14

Open yuanlii opened 4 years ago

yuanlii commented 4 years ago

connect to postgres db:

params = config()
conn = psycopg2.connect(**params)
cur = conn.cursor()
my_query = {}
#successfully connected to local postgres db
print ('Database connection established at ' + str(datetime.now()))

sample config file:

#!/usr/bin/python
from configparser import ConfigParser

def config(filename='./database.ini', section='postgresql'):
    # create a parser
    parser = ConfigParser()
    # read config file
    parser.read(filename)

    # get section, default to postgresql
    db = {}
    if parser.has_section(section):
        params = parser.items(section)
        for param in params:
            db[param[0]] = param[1]
    else:
        raise Exception('Section {0} not found in the {1} file'.format(section, filename))

    # import ipdb;ipdb.set_trace()
    return db