Java JDBC (Java Database Connectivity) is an application programming interface (API) for the Java programming language that provides a way to connect to & interact with databases.
Java JDBC enables Java programs to execute SQL statements and retrieve data from databases.
There are four types of JDBC drivers:
- JDBC-ODBC Bridge Driver: This driver provides JDBC access via an ODBC driver. It’s the first type of JDBC driver developed and is now considered outdated.
- Native-API Driver: This driver uses the client-side libraries of the database management system.
- Network Protocol Driver (Middleware Driver): This driver translates JDBC calls into a DBMS-independent network protocol, which is then translated to a DBMS-specific protocol by a server component.
- Thin Driver (Type 4 Driver): This is a pure Java driver that converts JDBC calls directly into the vendor-specific database protocol.
Here is a simple example of a Java program that uses JDBC to connect to a database and retrieve information about a car:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
import java.sql.*; public class CarExample { public static void main(String[] args) { Connection con = null; Statement stmt = null; ResultSet rs = null; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost/car_db", "root", "password"); stmt = con.createStatement(); rs = stmt.executeQuery("SELECT * FROM cars WHERE id = 1"); while (rs.next()) { String make = rs.getString("make"); String model = rs.getString("model"); int year = rs.getInt("year"); String color = rs.getString("color"); System.out.println("Make: " + make); System.out.println("Model: " + model); System.out.println("Year: " + year); System.out.println("Color: " + color); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (con != null) con.close(); } catch (Exception e) { e.printStackTrace(); } } } } |
In this example, we use the Class.forName
method to load the JDBC driver, the DriverManager.getConnection
method to establish a connection to the database, the createStatement
method to create a Statement
object, and the executeQuery
method to execute a SELECT statement and retrieve the result set. We then use the ResultSet
class to iterate through the rows of the result set and retrieve the values of the columns.