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 optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.