JDBC Drivers are software components that enable Java applications to communicate with databases. They act as a bridge between Java code and the database engine, translating JDBC method calls into database-specific instructions.
JDBC drivers are classified into four types based on how they interact with the database. Each type offers a trade-off between performance, portability, and ease of setup.
// Loading JDBC driver class
Class.forName("com.mysql.cj.jdbc.Driver");
// Establishing connection with database
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/studentdb","root","password"
);
// Creating statement object
Statement stmt = con.createStatement();
// Executing SQL query
ResultSet rs = stmt.executeQuery("SELECT * FROM students");
// Processing result set
while(rs.next()){
System.out.println(rs.getInt(1) + " " + rs.getString(2));
}
// Closing connection
con.close();
The JDBC driver loads first, then establishes a connection with the database. SQL commands are sent to the database, results are returned as a ResultSet, and finally resources are closed to prevent memory leaks.