JDBC stands for Java Database Connectivity. It is a standard Java API mainly used for accessing a relational database from a Java application. With JDBC, developers can perform various database operations like querying data, inserting/updating data, and executing database transactions. It provides a set of classes and interfaces to interact with different databases using SQL statements.
Here’s an example of JDBC implementation:
import java.sql.Connection;
import java.sql.DriverManager;
public class JdbcExample {
public static void main(String[] args) {
Connection conn = null;
try {
// Register JDBC driver
Class.forName(“com.mysql.jdbc.Driver”);
// Open connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection("jdbc:mysql://localhost/testdb","root", "password");
// Execute a query
System.out.println("Creating statement...");
Statement stmt = conn.createStatement();
String sql = "SELECT * FROM Employee";
ResultSet rs = stmt.executeQuery(sql);
// Extract data from result set
while(rs.next()) {
// Retrieve by column name
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
// Display values
System.out.print("ID: " + id);
System.out.print(", Name: " + name);
System.out.println(", Age: " + age);
}
// Free resources
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
// Close resources
try {
if (stmt != null)
stmt.close();
} catch (SQLException se) {
se.printStackTrace();
}
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
}
This example demonstrates how to connect to a MySQL database using JDBC, execute a SQL statement, and retrieve the records from the result set.
What is a JDBC driver?
Answer: A JDBC driver is a software component that enables communication between a Java application and a database management system.
What is the difference between a Type 1 and Type 4 JDBC driver?
Answer: A Type 1 JDBC driver translates JDBC calls into ODBC calls, while a Type 4 JDBC driver communicates directly with the database through a network protocol.
How do you connect to a database using JDBC?
Answer: To connect to a database using JDBC, you need to load the appropriate JDBC driver and then create a connection object using the DriverManager class.
What is a PreparedStatement in JDBC?
Answer: A PreparedStatement is a precompiled SQL statement that can be reused multiple times with different input parameters. It provides better performance and security compared to executing SQL statements directly.
How do you handle exceptions in JDBC?
Answer: In JDBC, you can handle exceptions using try-catch blocks or by letting the exception propagate to a higher level. Common exception types in JDBC include SQLException, BatchUpdateException, and DataTruncation.