Skip to content

Instantly share code, notes, and snippets.

@ahmedshahriar
Last active April 12, 2021 09:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmedshahriar/48fa5f32254252752ef715378e0cc882 to your computer and use it in GitHub Desktop.
Save ahmedshahriar/48fa5f32254252752ef715378e0cc882 to your computer and use it in GitHub Desktop.
Postgres initialization with Python. contains two script , 1. Postgres db config , 2. db connector
[postgresql]
host=localhost
database=my_db
user=postgres
password=postgres
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))
return db
def connect():
""" Connect to the PostgreSQL database server """
conn = None
try:
# read connection parameters
params = config()
# connect to the PostgreSQL server
print('Connecting to the PostgreSQL database...')
conn = psycopg2.connect(**params)
# create a cursor
cur = conn.cursor()
# execute a statement
print('PostgreSQL database version:')
cur.execute('SELECT version()')
# display the PostgreSQL database server version
db_version = cur.fetchone()
print(db_version)
# close the communication with the PostgreSQL
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
print('Database connection closed.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment