Skip to content

Instantly share code, notes, and snippets.

@DaWe35
Created August 16, 2019 11:37
Show Gist options
  • Save DaWe35/29ee520adf02788ed71c777494401197 to your computer and use it in GitHub Desktop.
Save DaWe35/29ee520adf02788ed71c777494401197 to your computer and use it in GitHub Desktop.
Test PostgreSQL server connection with Python 3
import sys
import logging
import psycopg2
class Database:
def __init__(self):
self.host = ''
self.username = ''
self.password = ''
self.port = '5432'
self.dbname = ''
self.conn = None
logging.basicConfig(level=logging.INFO)
def open_connection(self):
"""Connect to a Postgres database."""
try:
if(self.conn is None):
self.conn = psycopg2.connect(host=self.host,
user=self.username,
password=self.password,
port=self.port,
dbname=self.dbname)
except psycopg2.DatabaseError as e:
logging.error(e)
sys.exit()
finally:
logging.info('Connection opened successfully.')
p1 = Database()
p1.open_connection()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment