Hello All,
In python, should I connect to the database in constructor or in each module of the class? Suppose that I have 10 different module in my class which need to get or update the data from database. What do you recommend?
import oracledb
class DatabaseHandler:
def __init__(self, db_config):
"""Connect to Oracle database in the constructor."""
self.connection = oracledb.connect(user=db_config['user'], password=db_config['password'], dsn=db_config['dsn'])
self.cursor = self.connection.cursor()
def fetch_data(self, query):
"""Fetch data using the already established connection."""
self.cursor.execute(query)
return self.cursor.fetchall()
def close(self):
"""Close the connection and cursor."""
self.cursor.close()
self.connection.close()
db_config = {'user': 'username', 'password': 'password', 'dsn': 'dsn_string'}
db_handler = DatabaseHandler(db_config)
result = db_handler.fetch_data("SELECT * FROM some_table")
print(result)
db_handler.close()
import oracledb
class DatabaseHandler:
def fetch_data(self, query, db_config):
"""Connect to Oracle database in each method."""
connection = oracledb.connect(user=db_config['user'], password=db_config['password'], dsn=db_config['dsn'])
cursor = connection.cursor()
cursor.execute(query)
result = cursor.fetchall()
cursor.close()
connection.close()
return result
db_config = {'user': 'username', 'password': 'password', 'dsn': 'dsn_string'}
db_handler = DatabaseHandler()
result = db_handler.fetch_data("SELECT * FROM some_table", db_config)
print(result)
Thanks in advance