Created
August 16, 2019 11:37
-
-
Save DaWe35/29ee520adf02788ed71c777494401197 to your computer and use it in GitHub Desktop.
Test PostgreSQL server connection with Python 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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