0
0
JavaHow-ToBeginner · 4 min read

How to Connect to MySQL in Java: Simple Guide with Example

To connect to MySQL in Java, use the JDBC API by loading the MySQL driver with Class.forName and then create a connection using DriverManager.getConnection with your database URL, username, and password. This establishes a link between your Java program and the MySQL database for executing SQL commands.
📐

Syntax

Here is the basic syntax to connect to a MySQL database in Java using JDBC:

  • Load the driver: Class.forName("com.mysql.cj.jdbc.Driver") loads the MySQL driver class.
  • Establish connection: DriverManager.getConnection(url, user, password) opens the connection.
  • URL format: jdbc:mysql://hostname:port/databaseName specifies the database location.
java
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection(
    "jdbc:mysql://localhost:3306/mydatabase", "username", "password"
);
💻

Example

This example shows a complete Java program that connects to a MySQL database, prints a success message, and closes the connection.

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

public class MySQLConnectExample {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/mydatabase";
        String user = "root";
        String password = "password123";

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn = DriverManager.getConnection(url, user, password);
            System.out.println("Connected to MySQL database successfully!");
            conn.close();
        } catch (ClassNotFoundException e) {
            System.out.println("MySQL JDBC Driver not found.");
            e.printStackTrace();
        } catch (SQLException e) {
            System.out.println("Connection failed.");
            e.printStackTrace();
        }
    }
}
Output
Connected to MySQL database successfully!
⚠️

Common Pitfalls

  • Missing MySQL JDBC driver: Forgetting to add the MySQL Connector/J library to your project causes ClassNotFoundException.
  • Wrong URL format: The URL must start with jdbc:mysql:// and include the correct port and database name.
  • Incorrect credentials: Using wrong username or password leads to SQLException.
  • Not closing connections: Always close the connection to avoid resource leaks.
java
/* Wrong way: Missing driver load and wrong URL */
// Connection conn = DriverManager.getConnection("mysql://localhost:3306/db", "user", "pass");

/* Right way: Load driver and correct URL */
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db", "user", "pass");
📊

Quick Reference

Remember these key points when connecting Java to MySQL:

  • Use com.mysql.cj.jdbc.Driver for MySQL Connector/J 8.0 and above.
  • Database URL format: jdbc:mysql://host:port/database.
  • Handle ClassNotFoundException and SQLException properly.
  • Close your Connection after use to free resources.

Key Takeaways

Load the MySQL JDBC driver class before connecting.
Use the correct JDBC URL format with hostname, port, and database name.
Always handle exceptions for driver loading and connection errors.
Close the database connection to avoid resource leaks.
Add the MySQL Connector/J library to your project dependencies.