Created
March 30, 2021 06:09
-
-
Save carlosmmairena/836e6cd0ab624d783f91cbf588b6df7c to your computer and use it in GitHub Desktop.
Clase connection Python a PostgreSQL
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
[postgresql] | |
host=localhost | |
port=5432 | |
database=Example-DB | |
user=postgres | |
password=yourpostgresspwd |
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 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