How do I connect to a MySQL database using JDBC?

Connecting to a MySQL database using JDBC involves a few straightforward steps: adding the driver, defining your connection credentials, and using the DriverManager to open a session.

1. Add the MySQL Connector Dependency

First, ensure you have the MySQL JDBC driver in your project. If you are using Maven, add this to your pom.xml:

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>9.1.0</version> <!-- Use the latest version -->
</dependency>

2. Basic Connection Code

Here is a clean example of how to establish a connection and execute a simple query:

package org.kodejava.jdbc;

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

public class MySqlConnection {
    // JDBC URL: jdbc:mysql://[host]:[port]/[database_name]
    private static final String URL = "jdbc:mysql://localhost:3306/your_database";
    private static final String USER = "root";
    private static final String PASSWORD = "your_password";

    public static void main(String[] args) {
        // Try-with-resources automatically closes Connection, Statement, and ResultSet
        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)) {

            if (conn != null) {
                System.out.println("Connected to the database!");

                // Example: Execute a simple query
                String sql = "SELECT * FROM users";
                try (Statement stmt = conn.createStatement();
                     ResultSet rs = stmt.executeQuery(sql)) {

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

        } catch (SQLException e) {
            System.err.println("SQL State: " + e.getSQLState());
            System.err.println("Error Code: " + e.getErrorCode());
            System.err.println("Message: " + e.getMessage());
        }
    }
}

Key Components:

  • JDBC URL: For MySQL, it always starts with jdbc:mysql://. You can also append parameters like ?useSSL=false&serverTimezone=UTC to handle specific environment requirements.
  • DriverManager: The factory class that manages JDBC drivers and creates connections.
  • SQLException: Always wrap your JDBC code in a try-catch block, as database operations are prone to external failures (network issues, incorrect credentials, etc.).
  • Try-with-resources: In modern Java, you don’t need to manually call .close() in a finally block if you declare the resources inside the try (...) parentheses.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.