Introduction to JDBC (Java Database Connectivity)
JDBC (Java Database Connectivity) is a Java API used to connect Java applications with various databases such as MySQL, Oracle, SQL Server, PostgreSQL, and others. It provides classes and interfaces that allow developers to run SQL queries, retrieve results, update records, and manage transactions.
JDBC acts as a bridge between a Java application and a database, allowing Java programs to perform CRUD operations (Create, Read, Update, Delete) in a platform-independent manner.
Why Use JDBC?
- To connect Java applications with any relational database.
- To send SQL queries from Java to the database.
- To fetch, update, and delete data programmatically.
- Supports standardized and secure database access.
- Database-independent — same code runs on multiple databases.
Key Features of JDBC
- Platform-independent database connectivity
- Supports SQL execution
- Transaction management (commit/rollback)
- Batch processing
- PreparedStatement for secure parameterized queries
How JDBC Works?
JDBC works through a set of steps performed by the application:
- Load/Register JDBC driver
- Establish connection with database
- Create a statement object
- Execute SQL query
- Process the result
- Close the connection
try {
Class.forName("com.mysql.cj.jdbc.Driver"); // Step 1
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/testdb", "root", ""
); // Step 2
Statement stmt = con.createStatement(); // Step 3
ResultSet rs = stmt.executeQuery("SELECT * FROM students"); // Step 4
while(rs.next()) { // Step 5
System.out.println(rs.getInt(1) + " " + rs.getString(2));
}
con.close(); // Step 6
} catch(Exception e) {
e.printStackTrace();
}
JDBC Packages
The core JDBC API is found under:
java.sql.* // Core JDBC javax.sql.* // Advanced JDBC
Common JDBC Classes & Interfaces
| Name | Description |
|---|---|
DriverManager | Manages database drivers and connections |
Connection | Represents a database connection session |
Statement | Used for executing static SQL queries |
PreparedStatement | Used for dynamic, parameterized queries |
ResultSet | Represents data returned by SQL queries |
Real-Life Example
When you log in to a website, JDBC is used behind the scenes to:
- Fetch user details from database
- Validate credentials
- Store session data
- Retrieve user-specific records
Advantages of JDBC
- Simple API and easy to use
- Provides vendor-independent connectivity
- Allows secure parameterized SQL queries
- Supports transactions and batch operations
Conclusion
JDBC is the foundation for database programming in Java. It provides powerful APIs for executing SQL, retrieving results, and managing transactions. Learning JDBC is essential for building enterprise-level Java applications that interact with databases.
Login with Google