Lesson 7 | A sample program |
Objective | Write a simple yet complete JDBC program. |
Sample JDBC Program
Sample JDBC Program using Java SE 22 code to connect to a database using JDBC:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class Example1 {
public static void main(String[] args) {
// Load MySQL JDBC Driver
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Exception: Cannot load MySQL JDBC Driver");
e.printStackTrace(System.out);
return;
}
// Database connection details
String url = "jdbc:mysql://localhost:3306/mydatabase"; // Replace with your DB name
Properties props = new Properties();
props.setProperty("user", "myuser"); // Replace with your username
props.setProperty("password", "mypassword"); // Replace with your password
props.setProperty("serverTimezone", "UTC"); // Optional but recommended
// Connect using try-with-resources
try (Connection con = DriverManager.getConnection(url, props)) {
System.out.println("Connection established successfully to: " + url);
} catch (SQLException e) {
System.out.println("SQL Exception: " + e.getMessage());
e.printStackTrace(System.out);
}
}
}
🔍 Notes:
- ✅ Driver: Updated to
com.mysql.cj.jdbc.Driver
, required for MySQL 8.x and later.
- ✅ URL: Follows the modern JDBC URL pattern for MySQL.
- ✅ Properties:
user
, password
, and serverTimezone
handled with a Properties
object for clarity.
- ✅ Exception Handling: Robust and informative.
pom.xml snippet for Maven dependency management and MySQL connector
Here is the Maven
snippet you can include in your `pom.xml` to add the **MySQL Connector/J** driver:
<dependencies>
<!-- MySQL JDBC Driver for MySQL 8.x and above -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.3.0</version> <!-- Use the latest available version -->
</dependency>
</dependencies>
✅ Optional: Full Minimal `pom.xml` Template
If you are creating a new Maven project, here is a complete basic `pom.xml` structure with the MySQL dependency included:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>mysql-connection-example</artifactId>
<version>1.0.0</version>
<properties>
<maven.compiler.source>22</maven.compiler.source>
<maven.compiler.target>22</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.3.0</version>
</dependency>
</dependencies>
</project>
Details About the Connection
Establishing a connection to a database in Java SE 17 and later is simple and clean.
Using a
try-with-resources
block, you can obtain a connection through the
DriverManager
with a single line of code. The JDBC driver automatically handles
the registration process, so there's no need for manual driver loading.
Driver Registration in Java SE 17 and higher
- Driver registration is handled automatically at runtime through the
Java Service Provider Interface (SPI). As long as the JDBC driver is on the
application's classpath, it will be discovered and registered with the
DriverManager
without any developer intervention. This auto-registration is part
of the JDBC 4.0+ specification, which is fully supported in Java SE 17 and beyond.
The DriverManager
maintains a registry of all available JDBC drivers and selects
the appropriate one based on the connection URL provided. When you call
DriverManager.getConnection(...)
, it internally consults this list to find a
matching driver and establish the connection.
This streamlined approach helps you focus on writing functional data access code without
worrying about low-level driver mechanics.
Additional Registration Mechanisms
There are two additional mechanisms for registering drivers with the DriverManager. First, you could use
new to load and instantiate a driver directly in the application. This is usually not done because it is inflexible. It requires a recompile and potential rewrite of the code if the driver class changes. The second mechanism uses a feature of the DriverManager. The DriverManager will automatically register drivers referenced in the
jdbc.drivers property. Those properties can be specified either on the command line of the JVM or in a properties file.
- Alternative Connection
Finally, there is an alternative to the DriverManager for making a JDBC connection. The JDBC 2.0 specification provided for DataSources for making connections. You will explore those later in this course. The next lesson wraps up this module.
JDBC Connection - Exercise
