Advertisement
Fabio_LaF

Classe PgConnector

Aug 17th, 2022
459
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.44 KB | None | 0 0
  1. # file name: pgConnector.py
  2.  
  3. import psycopg2
  4.  
  5. class PgConnector:
  6.   def __init__(self, usr, pwd, db_name, print_flag):
  7.     try:
  8.       # connection to the database
  9.       self.connection = psycopg2.connect(
  10.         user = usr,
  11.         password = pwd,
  12.         host = "127.0.0.1",
  13.         port = "5432",
  14.         database = db_name
  15.       )
  16.       # used to perform database operations
  17.       self.cursor = self.connection.cursor()
  18.       self.print_flag = print_flag
  19.     except (Exception, psycopg2.Error) as error :
  20.       print ("Error while connecting to PostgreSQL", error)
  21.  
  22.   def __display_query(self, query):
  23.     str_max_size = 80
  24.  
  25.     if(self.print_flag == 'n'):
  26.       return
  27.     elif(self.print_flag == 'f' or len(query) <= str_max_size):
  28.       print("QUERY: " + query)
  29.     elif(self.print_flag == 's'):
  30.       print("QUERY: " + query[:str_max_size] + "...")
  31.  
  32.   def fetchless_query(self, query):
  33.     try:
  34.       self.__display_query(query)
  35.      
  36.       self.cursor.execute(query)
  37.     except (Exception, psycopg2.Error) as error :
  38.       print (error)
  39.  
  40.   def do_query(self, query):
  41.     try:
  42.       self.__display_query(query)
  43.      
  44.       self.cursor.execute(query)
  45.       return self.cursor.fetchall()
  46.     except (Exception, psycopg2.Error) as error :
  47.       print (error)
  48.  
  49.   def close(self):
  50.     if(self.connection):
  51.       self.cursor.close()
  52.       self.connection.close()
  53.       print("PostgreSQL connection is closed")
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement