1. What is JDBC?
Answer:
JDBC (Java Database Connectivity) is an API (Application Programming Interface) in Java that allows
Java applications to connect and interact with relational databases. It provides methods for querying
and updating data in the database, and is part of the Java Standard Edition (SE).
2. What are the key components of JDBC?
Answer:
The key components of JDBC include:
DriverManager: Manages a list of database drivers.
Connection: Represents the connection to the database.
Statement: Used to execute SQL queries against the database.
ResultSet: Represents the result of a query.
PreparedStatement: An optimized version of the Statement used for executing SQL queries
with parameters.
CallableStatement: Used to execute stored procedures in the database.
3. What are the types of JDBC Drivers?
Answer:
There are four types of JDBC drivers:
Type 1 - JDBC-ODBC Bridge Driver: Uses ODBC (Open Database Connectivity) to connect to a
database. It's deprecated in Java 8 and removed in Java 9.
Type 2 - Native API Driver: Uses database-specific native APIs to connect to a database.
Type 3 - Network Protocol Driver: Converts JDBC calls into a DBMS-independent network
protocol, which is then translated into the database's protocol by a middleware server.
Type 4 - Thin Driver: A pure Java driver that converts JDBC calls directly into the database's
native protocol. It’s the most widely used driver today.
4. What is the difference between Statement and PreparedStatement?
Answer:
Statement: Used for executing simple SQL queries without parameters. It is generally slower
than PreparedStatement because it requires the SQL query to be recompiled each time it is
executed.
PreparedStatement: Used for executing SQL queries with parameters. It is faster than
Statement because the SQL query is precompiled and cached by the database.
Example:
java
CopyEdit
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users WHERE username = 'john'");
PreparedStatement pstmt = connection.prepareStatement("SELECT * FROM users WHERE username
= ?");
pstmt.setString(1, "john");
ResultSet rs2 = pstmt.executeQuery();
5. What is the difference between execute(), executeQuery(), and executeUpdate()?
Answer:
execute(): Used for executing any SQL statement (SELECT, INSERT, UPDATE, DELETE, etc.). It
returns a boolean indicating whether the result is a ResultSet or not.
executeQuery(): Used specifically for executing SELECT queries. It returns a ResultSet
containing the result of the query.
executeUpdate(): Used for executing INSERT, UPDATE, DELETE, or other DML (Data
Manipulation Language) queries. It returns an integer indicating the number of affected
rows.
Example:
java
CopyEdit
Statement stmt = connection.createStatement();
stmt.executeUpdate("INSERT INTO users (username, password) VALUES ('john', 'password123')");
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
6. What is a Connection Pool?
Answer:
A Connection Pool is a collection of reusable connections to the database. It minimizes the overhead
of repeatedly opening and closing connections, improving performance. Connections are maintained
in the pool and reused as needed, and when the work is done, the connection is returned to the pool
rather than closed.
Example libraries for connection pooling:
Apache Commons DBCP
HikariCP
C3P0
7. What are the steps to establish a JDBC connection?
Answer: The steps to establish a JDBC connection are as follows:
1. Load the JDBC Driver: Load the appropriate JDBC driver using Class.forName().
2. Establish the Connection: Use DriverManager.getConnection() to establish a connection to
the database.
3. Create a Statement/PreparedStatement: Use the connection to create a statement or
prepared statement.
4. Execute the Query: Use the statement to execute the SQL query.
5. Process the Result: If the query is a SELECT query, process the ResultSet.
6. Close the Resources: Close the ResultSet, Statement, and Connection to free up resources.
Example:
java
CopyEdit
// Load the JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Establish the connection
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root",
"password");
// Create a statement and execute a query
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
// Process the result
while (rs.next()) {
System.out.println(rs.getString("username"));
// Close resources
rs.close();
stmt.close();
connection.close();
8. What is the purpose of the close() method in JDBC?
Answer:
The close() method is used to close JDBC resources like Connection, Statement, and ResultSet after
they are no longer needed. It is crucial to call close() to free up database connections and avoid
resource leaks.
9. What is a transaction in JDBC, and how do you manage it?
Answer:
A transaction in JDBC is a sequence of SQL statements that are executed as a single unit of work.
Transactions ensure data consistency and integrity. JDBC allows you to manage transactions through
methods on the Connection object:
setAutoCommit(false) to disable auto-commit mode.
commit() to commit the transaction.
rollback() to roll back the transaction in case of errors.
Example:
java
CopyEdit
connection.setAutoCommit(false); // Disable auto-commit
try {
Statement stmt = connection.createStatement();
stmt.executeUpdate("INSERT INTO users (username, password) VALUES ('john', 'password123')");
connection.commit(); // Commit the transaction
} catch (SQLException e) {
connection.rollback(); // Rollback in case of error
10. What is batch processing in JDBC?
Answer:
Batch processing in JDBC allows executing multiple SQL statements in a single batch, improving
performance by reducing the number of round-trips between the application and the database.
Example:
java
CopyEdit
connection.setAutoCommit(false);
Statement stmt = connection.createStatement();
stmt.addBatch("INSERT INTO users (username, password) VALUES ('john', 'password123')");
stmt.addBatch("INSERT INTO users (username, password) VALUES ('jane', 'password456')");
stmt.executeBatch();
connection.commit();
11. What is SQLExceptions in JDBC?
Answer:
SQLException is an exception class in JDBC that handles database-related errors. It provides detailed
information about database issues, such as connection failures, syntax errors, or constraint
violations.
12. What are the advantages of using JDBC?
Answer:
Platform Independence: JDBC allows Java applications to work with various databases.
Standardized Interface: Provides a common interface to interact with databases.
Scalability: JDBC supports a wide range of databases, making it scalable across different
environments.
Flexibility: Can be used to interact with different types of SQL databases and with different
connection types.