Implementing a database connection using a Singleton class in Java

Category : Design Patterns | Sub Category : Questions on Design Patterns | By Prasad Bonam Last updated: 2023-07-12 07:45:41 Viewed : 73

Implementing a database connection using a Singleton class in Java:

Here is an example of implementing a database connection using a Singleton class in Java:

public class DatabaseConnection { private static DatabaseConnection instance; private Connection connection; private DatabaseConnection() { // Initialize the database connection try { // Code to establish the database connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password"); } catch (SQLException e) { e.printStackTrace(); } } public static synchronized DatabaseConnection getInstance() { if (instance == null) { instance = new DatabaseConnection(); } return instance; } public Connection getConnection() { return connection; } // Other database-related methods... public void closeConnection() { try { if (connection != null) { connection.close(); } } catch (SQLException e) { e.printStackTrace(); } } }

In this example, the DatabaseConnection class is implemented as a Singleton using a private constructor and a static getInstance() method.

The DatabaseConnection class establishes a database connection in the constructor using JDBC. The connection is stored in the connection variable, which can be accessed through the getConnection() method.

To use the DatabaseConnection class, you can retrieve the singleton instance using DatabaseConnection.getInstance() and then call the relevant methods to interact with the database:

DatabaseConnection dbConnection = DatabaseConnection.getInstance(); Connection connection = dbConnection.getConnection(); // Use the connection to execute database queries // When finished, close the database connection dbConnection.closeConnection();

Note that this is a basic example to illustrate the Singleton pattern and database connection management. In a real-world scenario, you may need to handle connection pooling, exception handling, and other aspects specific to your database library and requirements. Additionally, consider using connection pooling libraries such as HikariCP or Apache Commons DBCP for efficient database connection management.

Related Articles

Leave a Comment: