Skip to Main Content

SQL & PL/SQL

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

Should I connect to Oracle in constructor or each module of a class?

ronald_2017Dec 30 2024 — edited Dec 30 2024

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

Comments
Post Details
Added on Dec 30 2024
3 comments
97 views