Java - JDBC - Connecting with MySQL

The steps for connecting to a MySQL database using Java Database Connectivity (JDBC):

  • Download and install the MySQL Connector/J JDBC driver from the MySQL website. You can find the download link here: https://dev.mysql.com/downloads/connector/j/
  • Create a new Java project in your preferred IDE (e.g. Eclipse, IntelliJ).
  • Import the Connector/J JDBC driver JAR file into your project. You can do this by right-clicking on your project in the Project Explorer, selecting "Build Path", then "Configure Build ath", and finally adding the JAR file to your project's classpath.
  • Open your code editor and create a new Java class for your database connection code. In this class, you'll need to do the following:
    • Import the required JDBC packages:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
    • Define the connection parameters (i.e. the database URL, username, and password) as constants:
private static final String DB_URL = "jdbc:mysql://localhost:3306/mydatabase";
private static final String USER = "myusername";
private static final String PASS = "mypassword";
    • Create a method for establishing a database connection:
public static Connection getConnection() throws SQLException {
    return DriverManager.getConnection(DB_URL, USER, PASS);
}

This method uses the DriverManager.getConnection() method to establish a connection to the database, using the connection parameters you defined earlier.

  • Now you can use the getConnection() method to establish a connection to your MySQL database from other parts of your Java code. For example:
try (Connection conn = MySQLConnection.getConnection()) {
    // Your database code here
} catch (SQLException e) {
    e.printStackTrace();
}

This example code uses a try-with-resources statement to automatically close the database connection when it's no longer needed.