DEV Community

Cover image for JDBC Utility Class for Managing MySQL Database Connections in Java
Michael Isijola
Michael Isijola

Posted on

JDBC Utility Class for Managing MySQL Database Connections in Java

This Java class DBConnection is a utility class designed to manage a database connection to a MySQL database using JDBC (Java Database Connectivity). This places the class in the com.mickeymuller.util package, indicating it's a utility helper class. These import essential JDBC classes: Connection: Represents a connection to the database. DriverManager: Handles creating connections to a database. SQLException: Exception thrown for database-related errors. This declares a public utility class called DBConnection. These are connection parameters: URL: Full JDBC URL to the local MySQL database mickeymuller_java. USER: MySQL username. PASSWORD: MySQL password. This is a static method, so it can be called without creating an object. It uses DriverManager.getConnection(...) to establish a database connection and returns a Connection object. It throws SQLException if connection fails. You can use this utility class whenever you want to get a connection to the MySQL database in your application. Important Note Don't hard-code your database password ("password") in production. Instead: Use environment variables Use encrypted secrets (e.g., via AWS Secrets Manager, Spring Vault, etc.)

package com.mickeymuller.util;

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

public class DBConnection {
    private static final String URL = "jdbc:mysql://localhost:3306/mickeymuller_java?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true";
    private static final String USER = "root";
    private static final String PASSWORD = "password";

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(URL, USER, PASSWORD);
    }

}
--------------------------------------------------

import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mickeymuller.util.DBConnection;

public class Main {
    public static void main(String[] args) {
        try (Connection conn = DBConnection.getConnection()) {
            System.out.println("✅ Database connected successfully!");

            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM users"); // assuming a table named `users`

            while (rs.next()) {
                System.out.println("User ID: " + rs.getInt("id"));
                System.out.println("Username: " + rs.getString("username"));
            }

        } catch (SQLException e) {
            System.err.println("❌ Database connection failed: " + e.getMessage());
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)