psycopg
Connecting to PostgreSQL
import psycopg2
import psycopg2.extras
conn = psycopg2.connect(database="doob", user = "ian", password = "pwd", host = "localhost")
print "Connection Successful"
#cur = conn.cursor()
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
query = "SELECT usename, usesuper FROM pg_user"
cur.execute(query)
rows = cur.fetchall()
for row in rows:
print(row)
print(f"{row['usename']} {row['usesuper']}")
cur.close()
Example Connection Files
Using Config Parser
# database.ini
[postgresql]
host=localhost
database=doob
user=ian
password=pwd
#!/usr/bin/python
from configparser import ConfigParser
def config(filename='database.ini', section='postgresql'):
parser = ConfigParser()
parser.read(filename)
params = parser.items(section)
for param in params:
db[param[0]] = param[1]
return db
#!/usr/bin/python
from config import config
def connect()
conn = None
try:
params = config()
conn = psycopg2.connect(**params)
cur = conn.cursor()
cur.execute('SELECT version()')
db_version = cur.fetchone()
print(db_version)
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
Using Credential File
# conndetails.py
PGHOST="localhost"
PGDATABASE="doob"
PGUSER="ian"
PGPASSWORD="pwd"
import psycopg2
import conndetails as creds
conn_string = "host="+ creds.PGHOST +" dbname="+ creds.PGDATABASE +" user="
+ creds.PGUSER +" password="+ creds.PGPASSWORD
conn = psycopg2.connect(conn_string)
cur = conn.cursor()
query = "select version()"
cur.execute(query)
for row in cur:
print(row)
cur.close()