JDBC Database Connectivity - Complete Detailed
Guide
Introduction
Java Database Connectivity (JDBC) is a Java API that allows Java applications to connect and
interact with databases. It provides methods to execute SQL queries and retrieve results from
databases like MySQL, Oracle, PostgreSQL, etc.
JDBC Connectivity Flow Diagram
Start
↓
Register JDBC Driver
↓
Create Connection
↓
Create Statement
↓
Execute Query
↓
Process Result
↓
Close Resources
↓
End
Step 1: Register the Driver Class
The driver class loads the JDBC driver into memory. It acts as a bridge between Java application
and the database.
[Link]("[Link]");
Step 2: Create Connection
Connection object represents a session between Java application and database. You must provide
URL, username, and password.
Connection con = [Link](
"jdbc:mysql://localhost:3306/mydatabase",
"root",
"password"
);
Step 3: Create Statement
Statement object is used to execute SQL queries.
Statement stmt = [Link]();
Step 4: Execute Query
Execute SQL queries using executeQuery() for SELECT and executeUpdate() for INSERT,
UPDATE, DELETE.
ResultSet rs = [Link]("SELECT * FROM customers");
while([Link]()) {
[Link]([Link]("name") +
" " + [Link]("age"));
}
Step 5: Close Connection
Close ResultSet, Statement, and Connection to free resources. It is best practice to use
try-with-resources in Java 7+.
[Link]();
[Link]();
[Link]();
Using Try-With-Resources (Recommended)
try(Connection con = [Link](url, user, pass);
Statement stmt = [Link]();
ResultSet rs = [Link]("SELECT * FROM customers")) {
while([Link]()) {
[Link]([Link]("name"));
}
}
Advantages of JDBC
1 Platform Independent
2 Supports Multiple Databases
3 Simple and Secure
4 Efficient Resource Management
5 Supports Connection Pooling
Conclusion
JDBC provides a simple and powerful way to connect Java applications with databases. By
following the 5 steps (Register Driver, Create Connection, Create Statement, Execute Query, Close
Connection), developers can build dynamic and database-driven applications efficiently.