You are currently viewing How to Connect to a MySQL Database in Java

How to Connect to a MySQL Database in Java

When working with MySQL databases in Java, you need to have the MySQL JDBC driver, also known as Connector/J. This driver provides a way for Java programs to communicate with a MySQL database by translating Java method calls into SQL statements that MySQL can understand.

Downloading The MySQL Connector

To download Connector/J, the official MySQL JDBC driver, for all platforms, go to the official MySQL Connector/J download page. From there, select the version of Connector/J that you need, then choose the appropriate download option based on your operating system. Typically, you will want to download the .zip or .tar.gz archive file, which contains the Connector/J jar files. Extract the contents of the archive to a location on your computer, and then add the Connector/J jar files to your Java project’s classpath. This will allow you to connect to MySQL databases using the Connector/J driver in your Java code.

Connecting to MySQL

The demonstrated Java code below establishes a JDBC connection to a MySQL database, and retrieves data from the “users” table. The connection details are defined as constants at the beginning of the code. The code uses a try-with-resources block to ensure the resources are properly closed after use. The SQL query to retrieve data from the “users” table is defined as a string variable, and then executed using a PreparedStatement. The results of the query are then iterated over using a while loop, and the values of each row are retrieved using the ResultSet object. Finally, the retrieved values are printed to the console.

import java.sql.*;

public class Main {

    // define the connection details as constants
    private static final String HOSTNAME = "localhost";
    private static final String PORT     = "3306";
    private static final String DATABASE = "scratchpad";
    private static final String USER     = "root";
    private static final String PASSWORD = "";

    public static void main(String[] args) {

        // create the JDBC URL based on the connection details
        String url = String.format("jdbc:mysql://%s:%s/%s", HOSTNAME, PORT, DATABASE);

        try (Connection connection = DriverManager.getConnection(url, USER, PASSWORD)) {

            // define the SQL query to execute
            String sql = "SELECT * FROM users";

            // prepare the statement and execute the query
            try (
                    PreparedStatement statement = connection.prepareStatement(sql);
                    ResultSet resultSet = statement.executeQuery()
            ) {

                // iterate over the results and print them to the console
                while (resultSet.next()) {

                    int id = resultSet.getInt("id");
                    String name = resultSet.getString("name");
                    String email = resultSet.getString("email");

                    System.out.printf("%d, %s, %s%n", id, name, email);

                }

            }

        } catch (SQLException sqlException) {

            // handle any errors that occur during the connection or query
            sqlException.printStackTrace();

        }

    }

}

Conclusion

In conclusion, understanding how to connect to and query a MySQL database using JDBC can be a valuable skill for any Java developer. The code example above provides a simple and concise demonstration of how to connect to a MySQL database and execute a basic SELECT statement using JDBC. With this knowledge, developers can build more complex database-driven applications, from small personal projects to enterprise-level systems. Whether you’re just starting out or looking to expand your skill set, JDBC and MySQL are powerful tools to add to your toolkit. We hope this example has been helpful in getting you started with JDBC and MySQL. If you wish to learn more about Java, please subscribe to our newsletter today and continue your Java learning journey with us!

Leave a Reply