Skip to content

Instantly share code, notes, and snippets.

@carlosmmairena
Created March 30, 2021 06:09
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 carlosmmairena/836e6cd0ab624d783f91cbf588b6df7c to your computer and use it in GitHub Desktop.
Save carlosmmairena/836e6cd0ab624d783f91cbf588b6df7c to your computer and use it in GitHub Desktop.
Clase connection Python a PostgreSQL
[postgresql]
host=localhost
port=5432
database=Example-DB
user=postgres
password=yourpostgresspwd
import psycopg2
from configparser import ConfigParser
class Postgres():
""" Connect to the PostgreSQL database server """
connection = None
def __init__(self):
try:
params = self.config()
if self.connection is None:
print('Connecting to the PostgreSQL database...')
self.connection = psycopg2.connect(**params)
except (Exception, psycopg2.DatabaseError) as error:
print(error)
def config(self, filename='config.ini', section='postgresql'):
parser = ConfigParser()
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 return_connection(self):
if self.connection is not None:
return self.connection
else: return None
def cerrar_conexion(self):
if self.connection is not None:
self.connection.close()
print('Database connection closed.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment