JDBC · Lesson 2
JDBC Architecture and Drivers
What JDBC Provides
JDBC is the standard Java API for communicating with relational databases. It defines interfaces for connections, statements, results, and transactions while database vendors supply driver implementations. This separation lets application code use a consistent programming model across supported databases.
JDBC Layers
An application uses JDBC interfaces, a driver translates those calls into a database protocol, and the database executes the SQL. The DriverManager is suitable for simple examples, while a DataSource is preferred for managed applications.
import java.sql.Connection;
import java.sql.DriverManager;
public class DriverConnectionDemo {
public static void main(String[] arguments) throws Exception {
String databaseUrl = "jdbc:h2:mem:academy";
try (Connection connection = DriverManager.getConnection(databaseUrl, "sa", "")) {
System.out.println("Connected: " + !connection.isClosed());
System.out.println("Database: " + connection.getMetaData().getDatabaseProductName());
}
}
}
Driver and API Comparison
| Component | Responsibility | Example |
|---|---|---|
| JDBC API | Common Java interfaces | Connection, ResultSet |
| Driver | Translates JDBC calls | PostgreSQL JDBC driver |
DriverManager | Finds and opens drivers | Simple command-line app |
DataSource | Managed connection factory | Web application and pool |
Common Mistake and Practices
Common Mistake: Treating the JDBC driver as optional runtime configuration. The application may compile successfully but fail when it first tries to connect if the driver is absent from the runtime classpath.
- Keep the driver dependency in the runtime build.
- Use a
DataSourcefor server applications. - Keep credentials outside source code.
- Close connections with try-with-resources.
- Verify driver and database version compatibility.
Real-World Use Case
A reporting service uses the same JDBC interfaces in local tests and production, changing only the driver and connection configuration. The repository code remains focused on queries rather than vendor-specific socket details.
Quiz Check