Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # file name: pgConnector.py
- import psycopg2
- class PgConnector:
- def __init__(self, usr, pwd, db_name, print_flag):
- try:
- # connection to the database
- self.connection = psycopg2.connect(
- user = usr,
- password = pwd,
- host = "127.0.0.1",
- port = "5432",
- database = db_name
- )
- # used to perform database operations
- self.cursor = self.connection.cursor()
- self.print_flag = print_flag
- except (Exception, psycopg2.Error) as error :
- print ("Error while connecting to PostgreSQL", error)
- def __display_query(self, query):
- str_max_size = 80
- if(self.print_flag == 'n'):
- return
- elif(self.print_flag == 'f' or len(query) <= str_max_size):
- print("QUERY: " + query)
- elif(self.print_flag == 's'):
- print("QUERY: " + query[:str_max_size] + "...")
- def fetchless_query(self, query):
- try:
- self.__display_query(query)
- self.cursor.execute(query)
- except (Exception, psycopg2.Error) as error :
- print (error)
- def do_query(self, query):
- try:
- self.__display_query(query)
- self.cursor.execute(query)
- return self.cursor.fetchall()
- except (Exception, psycopg2.Error) as error :
- print (error)
- def close(self):
- if(self.connection):
- self.cursor.close()
- self.connection.close()
- print("PostgreSQL connection is closed")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement