JDBC Connectivity with MySQL


You must have the following to establish a Java application connection to MySQL Database through JDBC:

  • You need MySQL installed on your system or access to a MySQL server to connect a Java application with a MySQL Database using JDBC.
  • MySQL JDBC driver (mysql-connector-java)
  • Correct credentials and database name

Download MySQL JDBC Driver

  • Get the mysql-connector-java.jar from MySQL official site
  • Add it to your project’s classpath

OR Use Maven Dependency

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.33</version>
</dependency>

JDBC Connection URL Format

jdbc:mysql://host:port/database_name 

Example

String url = "jdbc:mysql://localhost:3306/testdb";
String username = "root";
String password = "password";
 

Example

import java.sql.*;

public class MySQLJDBCExample {
    public static void main(String[] args) {
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            // Step 1: Load MySQL JDBC Driver
            Class.forName("com.mysql.cj.jdbc.Driver");

            // Step 2: Create connection
            con = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/testdb", // DB URL
                "root",                               // Username
                "password"                            // Password
            );

            // Step 3: Create statement
            stmt = con.createStatement();

            // Step 4: Execute query
            rs = stmt.executeQuery("SELECT * FROM employees");

            // Step 5: Process result set
            while (rs.next()) {
                System.out.println(rs.getInt("id") + " - " + rs.getString("name"));
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // Step 6: Close resources
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
                if (con != null) con.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }
} 

Common Issues

Issue Solution
ClassNotFoundException Ensure MySQL JAR is in your classpath
Communications link failure Check DB server is running and connection string is correct
Access denied for user Verify username/password and DB permissions
Public Key Retrieval is not allowed Add ?allowPublicKeyRetrieval=true&useSSL=false to your URL



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.