JDBCUtil Class (in util package)

129


package util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JDBCUtil {

// Database URL, username, and password
private static final String URL = "jdbc:derby:D:\\Users\\2725945\\MyDB;create=true";
private static final String DRIVER_NAME = "org.apache.derby.jdbc.EmbeddedDriver";
private static Connection connection = null;

static {
    try {
        // Load the JDBC driver
        Class.forName(DRIVER_NAME);
    } catch (ClassNotFoundException e) {
        System.err.println("Error loading JDBC Driver: " + e.getMessage());
    }
}

// Method to establish and return a connection
public static Connection getConnection() throws SQLException {
    if (connection == null || connection.isClosed()) {
        connection = DriverManager.getConnection(URL);
        System.out.println("Connection established successfully.");
    }
    return connection;
}

// Method to close the connection
public static void closeConnection() {
    try {
        if (connection != null && !connection.isClosed()) {
            connection.close();
            System.out.println("Connection closed.");
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

}