JDBC Basics for Beginners
What is JDBC?
JDBC (Java Database Connectivity) is a Java API that allows Java applications to connect with databases such as PostgreSQL, MySQL, Oracle, and SQL Server.
Using JDBC, we can:
- Connect to a database
- Execute SQL queries
- Insert, update, and delete records
- Retrieve data from tables
JDBC Architecture
Java Application
|
v
JDBC API
|
v
JDBC Driver
|
v
Database
The JDBC Driver acts as a bridge between the Java application and the database.
JDBC Steps
Step 1: Load the Driver
Class.forName("org.postgresql.Driver");
This loads the PostgreSQL JDBC driver into memory.
Step 2: Create a Connection
Connection con = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/postgres",
"postgres",
"password"
);
This creates a connection between Java and PostgreSQL.
Step 3: Create a Statement
Statement stmt = con.createStatement();
A Statement object is used to execute SQL queries.
Step 4: Execute Query
ResultSet rs = stmt.executeQuery(
"SELECT * FROM india_players"
);
The query is sent to the database and the result is stored in a ResultSet.
Step 5: Read Data
while(rs.next()) {
System.out.println(
rs.getString("player_name")
);
}
The next() method moves through each row and retrieves data.
Step 6: Close Resources
rs.close();
stmt.close();
con.close();
Closing resources helps prevent memory leaks.
Example Program
import java.sql.*;
public class JdbcDemo {
public static void main(String[] args) {
try {
Class.forName("org.postgresql.Driver");
Connection con = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/postgres",
"postgres",
"password"
);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(
"SELECT * FROM india_players"
);
while(rs.next()) {
System.out.println(
rs.getString("player_name")
);
}
rs.close();
stmt.close();
con.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
Important JDBC Classes
| Class | Purpose |
|---|---|
| DriverManager | Creates database connections |
| Connection | Represents a database connection |
| Statement | Executes SQL queries |
| ResultSet | Stores query results |
Conclusion
JDBC is the standard API used to connect Java applications with databases. The basic JDBC flow is:
- Load Driver
- Create Connection
- Create Statement
- Execute Query
- Read ResultSet
- Close Resources
Understanding these six steps is enough to start working with JDBC and database-driven Java applications.
Top comments (0)