Project Setup
Before you can write a single line of JDBC code, the driver jar for your database needs to be available to your Java program at compile and run time. There are two common ways to do this: add the jar to your classpath by hand, or let a build tool pull it in for you as a dependency.
Option 1: Manual Jar on the Classpath
This is the simplest way to get started, especially if you're just running a single .java file to
experiment. Download the driver jar (for example mysql-connector-j-8.x.x.jar from MySQL's site),
place it somewhere in your project, and tell javac/java where to find it with
-cp.
Example: Compiling and Running With the Driver on the Classpath
// Compile your program together with the driver jar on the classpath
javac -cp ".;mysql-connector-j-8.3.0.jar" App.java
// Run it the same way (use ":" instead of ";" on Linux/Mac)
java -cp ".;mysql-connector-j-8.3.0.jar" App
Option 2: A Build Tool Dependency (the Modern Way)
Most real Java projects use a build tool like Maven or Gradle to manage dependencies instead of downloading jars
by hand. You just declare which driver and version you want, and the build tool downloads it and wires it into
your classpath automatically. Here's what that declaration looks like in a Maven pom.xml:
Example: MySQL Connector/J as a Maven Dependency
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.3.0</version>
</dependency>
pom.xml that already exists.The JDBC URL Format
Whichever way you add the driver, you'll need a JDBC URL to connect. It generally follows this shape:
jdbc:mysql://host:port/database
For example, jdbc:mysql://localhost:3306/coding_with_sonu connects to a database named
coding_with_sonu running on the local MySQL server's default port.
Do You Still Need Class.forName?
Since JDBC 4.0 (Java 6 and later), DriverManager can automatically discover any driver jar that's on
the classpath — it uses Java's ServiceLoader mechanism behind the scenes, so you often don't need to
load the driver class yourself at all.
Class.forName(...) explicitly before connecting. It's no longer required on modern JDBC, but it's harmless, and you'll see it constantly, so here's the old-style pattern:Example: Old-Style Explicit Driver Loading
public class DriverLoadExample {
public static void main(String[] args) throws Exception {
// Not required since JDBC 4.0, but still common in older code
Class.forName("com.mysql.cj.jdbc.Driver");
}
}