Introduction to JDBC in Java
JDBC is the standard Java API for connecting to relational databases, executing SQL queries, and processing results. It is essential for backend Java developers building data-driven applications.
What Is JDBC?
JDBC provides a vendor-neutral interface between Java code and database management systems. You write Java code against JDBC interfaces; database vendors supply JDBC drivers that translate calls to their native protocol.
JDBC Architecture
Java Application
Your code using JDBC API (Connection, Statement, ResultSet).
JDBC Driver
Vendor-specific driver (MySQL Connector/J, PostgreSQL JDBC).
Database
MySQL, PostgreSQL, Oracle, SQL Server, etc.
Basic JDBC Steps
- Load the JDBC driver (or use DriverManager with JDBC 4+ auto-loading).
- Establish a Connection with DriverManager.getConnection(url, user, password).
- Create a Statement or PreparedStatement.
- Execute SQL and process the ResultSet.
- Close resources in finally block or try-with-resources.
Hello JDBC Example
String url = "jdbc:mysql://localhost:3306/mydb";
try (Connection conn = DriverManager.getConnection(url, "user", "pass");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT id, name FROM users")) {
while (rs.next()) {
System.out.println(rs.getInt("id") + ": " + rs.getString("name"));
}
}Frequently Asked Questions
Do I need to install JDBC separately?▼
JDBC is part of the JDK (java.sql package). You need to add the database-specific driver JAR (e.g., mysql-connector-j) to your classpath or Maven/Gradle dependencies.
