JDBC Connect

Establishing database connections in Java

🔗 Database Connection

JDBC connection establishes a session with a specific database. You need database URL, username, and password to create a connection using DriverManager.getConnection() method.


// Basic connection example
Connection conn = DriverManager.getConnection(
    "jdbc:mysql://localhost:3306/mydb", 
    "username", 
    "password"
);
                                    

Connection Methods

🌐

URL Connection

Connect using database URL

DriverManager.getConnection(url, user, pass);
📋

Properties

Connect using Properties object

Properties props = new Properties();
DriverManager.getConnection(url, props);
🏊

Connection Pool

Reuse connections efficiently

DataSource ds = new HikariDataSource();
Connection conn = ds.getConnection();
🔒

SSL Connection

Secure database connections

url += "?useSSL=true&requireSSL=true";

🔹 Basic Connection Example

Simple database connection with error handling:

import java.sql.*;

public class DatabaseConnection {
    public static void main(String[] args) {
        // Database credentials
        String url = "jdbc:mysql://localhost:3306/testdb";
        String username = "root";
        String password = "password";
        
        Connection connection = null;
        
        try {
            // Load MySQL driver (optional in newer versions)
            Class.forName("com.mysql.cj.jdbc.Driver");
            
            // Establish connection
            connection = DriverManager.getConnection(url, username, password);
            
            if (connection != null) {
                System.out.println("Connected to MySQL database!");
                System.out.println("Database: " + connection.getCatalog());
            }
            
        } catch (ClassNotFoundException e) {
            System.out.println("MySQL Driver not found: " + e.getMessage());
        } catch (SQLException e) {
            System.out.println("Connection failed: " + e.getMessage());
        } finally {
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                    System.out.println("Connection closed successfully.");
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

Output:

Connected to MySQL database!

Database: testdb

Connection closed successfully.

🔹 Connection URLs for Different Databases

Database-specific connection URL formats:

// MySQL
String mysqlUrl = "jdbc:mysql://localhost:3306/database_name";

// PostgreSQL
String postgresUrl = "jdbc:postgresql://localhost:5432/database_name";

// Oracle
String oracleUrl = "jdbc:oracle:thin:@localhost:1521:xe";

// SQL Server
String sqlServerUrl = "jdbc:sqlserver://localhost:1433;databaseName=database_name";

// SQLite
String sqliteUrl = "jdbc:sqlite:path/to/database.db";

// H2 Database (In-memory)
String h2Url = "jdbc:h2:mem:testdb";

// Example with parameters
String urlWithParams = "jdbc:mysql://localhost:3306/mydb" +
                      "?useSSL=false" +
                      "&serverTimezone=UTC" +
                      "&allowPublicKeyRetrieval=true";

🔹 Connection with Properties

Using Properties object for connection parameters:

import java.sql.*;
import java.util.Properties;

public class PropertiesConnection {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/testdb";
        
        // Create properties object
        Properties props = new Properties();
        props.setProperty("user", "root");
        props.setProperty("password", "password");
        props.setProperty("useSSL", "false");
        props.setProperty("serverTimezone", "UTC");
        props.setProperty("autoReconnect", "true");
        
        try {
            // Connect using properties
            Connection conn = DriverManager.getConnection(url, props);
            
            System.out.println("Connected using Properties!");
            System.out.println("Auto-commit: " + conn.getAutoCommit());
            
            conn.close();
            
        } catch (SQLException e) {
            System.out.println("Connection error: " + e.getMessage());
        }
    }
}

Output:

Connected using Properties!

Auto-commit: true

🔹 Connection Utility Class

Reusable connection utility for better code organization:

import java.sql.*;

public class DatabaseUtil {
    private static final String URL = "jdbc:mysql://localhost:3306/testdb";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "password";
    
    // Get database connection
    public static Connection getConnection() throws SQLException {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            return DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (ClassNotFoundException e) {
            throw new SQLException("Database driver not found", e);
        }
    }
    
    // Close connection safely
    public static void closeConnection(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
                System.out.println("Connection closed.");
            } catch (SQLException e) {
                System.out.println("Error closing connection: " + e.getMessage());
            }
        }
    }
    
    // Test connection
    public static void main(String[] args) {
        Connection conn = null;
        try {
            conn = getConnection();
            System.out.println("Database connection successful!");
            
        } catch (SQLException e) {
            System.out.println("Connection failed: " + e.getMessage());
        } finally {
            closeConnection(conn);
        }
    }
}

Output:

Database connection successful!

Connection closed.

🧠 Test Your Knowledge

Which method is used to establish a database connection?