Adv-Java Unit 3: Questions & Answers
Unit 3: The Concept of JDBC -> Generated and Prepared By Thiruselvan (ThiruXD)
SECTION A: MULTIPLE CHOICE QUESTIONS (50 MCQs)
Introduction to JDBC
Q1. What does JDBC stand for?
- Java Database Connectivity
- Java Data Control
- Java Dynamic Connection
- Java Database Component
Answer: A) Java Database Connectivity -> Explanation: JDBC stands for Java Database Connectivity. It is a Java API that allows Java applications to connect to databases, execute SQL queries, and process results.
Q2. Which package contains the core JDBC classes and interfaces?
java.dbjava.sqljavax.jdbcjava.database
Answer: B) java.sql -> Explanation: The java.sql package contains core JDBC classes and interfaces such as Connection, Statement, PreparedStatement, CallableStatement, and ResultSet.
Q3. JDBC acts as a bridge between:
- Two Java applications
- Java applications and databases
- Two databases
- Java and HTML
Answer: B) Java applications and databases -> Explanation: JDBC acts as a bridge between Java applications and databases. It translates Java calls into database-specific calls via the JDBC driver.
Q4. Which class is used to create database connections in JDBC?
ConnectionDriverManagerStatementResultSet
Answer: B) DriverManager -> Explanation: DriverManager is the class used to create database connections. It manages JDBC drivers and provides the getConnection() method.
Q5. Which of the following is NOT an advantage of JDBC?
- Platform independent
- Database independent
- Requires ODBC installation
- Standard API
Answer: C) Requires ODBC installation -> Explanation: Requiring ODBC installation is a limitation of Type 1 drivers, not an advantage of JDBC. JDBC’s advantages include platform independence, database independence, and a standard API.
Q6. What is the correct order of the JDBC workflow?
- Driver → JDBC → Application → Database
- Java Application → JDBC → JDBC Driver → Database
- Database → JDBC → Driver → Application
- JDBC → Database → Driver → Application
Answer: B) Java Application → JDBC → JDBC Driver → Database -> Explanation: The JDBC workflow is: Java Application → JDBC → JDBC Driver → Database. JDBC provides the API, the driver translates calls, and the database executes them.
JDBC Driver Types
Q7. Which JDBC driver type uses the JDBC-ODBC bridge?
- Type 1
- Type 2
- Type 3
- Type 4
Answer: A) Type 1 -> Explanation: Type 1 is the JDBC-ODBC Bridge Driver. It uses ODBC to connect to databases. It was removed after Java 8 due to performance and platform dependency issues.
Q8. Which JDBC driver type is known as the “Thin Driver”?
- Type 1
- Type 2
- Type 3
- Type 4
Answer: D) Type 4 -> Explanation: Type 4 is known as the Thin Driver. It is a pure Java driver that communicates directly with the database, making it the fastest and most portable.
Q9. Which driver type is the fastest and most commonly used?
- Type 1
- Type 2
- Type 3
- Type 4
Answer: D) Type 4 -> Explanation: Type 4 (Thin Driver) is the fastest, pure Java, portable, and most commonly used driver in modern applications.
Q10. Which driver type uses a middleware server?
- Type 1
- Type 2
- Type 3
- Type 4
Answer: C) Type 3 -> Explanation: Type 3 (Network Protocol Driver) uses a middleware server between the Java application and the database. It is database independent but requires an additional server.
Q11. Which driver type uses native database libraries?
- Type 1
- Type 2
- Type 3
- Type 4
Answer: B) Type 2 -> Explanation: Type 2 (Native API Driver) uses native database libraries. It is faster than Type 1 but requires native installation on the client machine.
Q12. Which driver type was removed after Java 8?
- Type 1
- Type 2
- Type 3
- Type 4
Answer: A) Type 1 -> Explanation: The Type 1 JDBC-ODBC Bridge Driver was removed after Java 8 because it was platform dependent, slow, and required ODBC installation.
Q13. Which driver type is platform dependent?
- Type 1 and Type 2
- Type 3 and Type 4
- Only Type 1
- Only Type 4
Answer: A) Type 1 and Type 2 -> Explanation: Type 1 and Type 2 drivers are platform dependent because they rely on ODBC or native database libraries. Type 3 and Type 4 are platform independent.
JDBC Packages and Interfaces
Q14. Which package provides advanced JDBC features like connection pooling?
java.sqljavax.sqljava.jdbcjavax.db
Answer: B) javax.sql -> Explanation: The javax.sql package provides advanced JDBC features such as Connection Pooling, RowSet, and DataSource.
Q15. Which interface represents an active connection with the database?
StatementResultSetConnectionDriverManager
Answer: C) Connection -> Explanation: The Connection interface represents an active connection with the database. It is obtained via DriverManager.getConnection().
Q16. Which interface is used to execute simple SQL queries?
ConnectionStatementResultSetDriverManager
Answer: B) Statement -> Explanation: The Statement interface is used to execute simple SQL queries. It is created via con.createStatement().
Q17. Which interface stores query results?
StatementConnectionResultSetDriverManager
Answer: C) ResultSet -> Explanation: The ResultSet interface stores the results of a SQL query. It provides methods like next(), getString(), and getInt().
Q18. Which class handles database exceptions in JDBC?
SQLExceptionIOExceptionDatabaseExceptionJDBCException
Answer: A) SQLException -> Explanation: SQLException is the class that handles database exceptions in JDBC. It provides methods like getMessage() and getErrorCode().
Q19. Which interface is used to call stored procedures?
StatementPreparedStatementCallableStatementConnection
Answer: C) CallableStatement -> Explanation: CallableStatement is used to call stored procedures in the database. It is created via con.prepareCall("{call procedureName()}").
JDBC Process
Q20. What is the first step in the JDBC process?
- Establish connection
- Load driver
- Execute query
- Process result
Answer: B) Load driver -> Explanation: The first step in the JDBC process is to load the driver using Class.forName("com.mysql.cj.jdbc.Driver").
Q21. Which method is used to load a JDBC driver?
DriverManager.load()Class.forName()Connection.load()Driver.load()
Answer: B) Class.forName() -> Explanation: Class.forName() is used to load a JDBC driver class into memory. Example: Class.forName("com.mysql.cj.jdbc.Driver").
Q22. Which method is used to establish a connection?
DriverManager.getConnection()Connection.open()Driver.connect()Statement.connect()
Answer: A) DriverManager.getConnection() -> Explanation: DriverManager.getConnection(url, user, password) is used to establish a connection to the database.
Q23. What is the correct MySQL connection URL format?
jdbc:mysql://host:port/databasemysql:jdbc://host:port/databasejdbc://mysql:host:port/databasejdbc:mysql:host:port/database
Answer: A) jdbc:mysql://host:port/database -> Explanation: The correct MySQL connection URL format is jdbc:mysql://host:port/database. Example: jdbc:mysql://localhost:3306/test.
Q24. What is the default port number for MySQL?
- 1521
- 3306
- 5432
- 8080
Answer: B) 3306 -> Explanation: MySQL’s default port number is 3306. Oracle uses 1521, PostgreSQL uses 5432, and Tomcat uses 8080.
Q25. Which method is used to execute a SELECT query?
executeUpdate()executeQuery()execute()executeSelect()
Answer: B) executeQuery() -> Explanation: executeQuery() is used to execute SELECT queries. It returns a ResultSet object containing the query results.
Q26. Which method is used to execute INSERT, UPDATE, or DELETE queries?
executeQuery()executeUpdate()execute()executeModify()
Answer: B) executeUpdate() -> Explanation: executeUpdate() is used to execute INSERT, UPDATE, or DELETE queries. It returns an int representing the number of affected rows.
Q27. What is the last step in the JDBC process?
- Execute query
- Process result
- Close resources
- Load driver
Answer: C) Close resources -> Explanation: The last step in the JDBC process is to close resources (ResultSet, Statement, Connection) to avoid memory leaks.
Q28. Which method moves the ResultSet cursor to the next row?
next()previous()first()move()
Answer: A) next() -> Explanation: next() moves the ResultSet cursor to the next row. It returns true if a row exists and false when no more rows are available.
PreparedStatement and CallableStatement
Q29. What is a PreparedStatement?
- A statement that is precompiled
- A statement that is executed once
- A statement that cannot accept parameters
- A statement for stored procedures
Answer: A) A statement that is precompiled -> Explanation: A PreparedStatement is a precompiled SQL statement. The SQL is compiled once and can be executed multiple times with different parameters.
Q30. Which method is used to set an integer parameter in PreparedStatement?
setInt()setInteger()setNumber()setValue()
Answer: A) setInt() -> Explanation: setInt(index, value) is used to set an integer parameter in a PreparedStatement. Example: ps.setInt(1, 101).
Q31. Which is a major advantage of PreparedStatement?
- Slower execution
- Prevents SQL injection
- Cannot be reused
- Requires no parameters
Answer: B) Prevents SQL injection -> Explanation: PreparedStatement prevents SQL injection because parameters are escaped and treated as data, not as part of the SQL statement.
Q32. Which method is used to create a CallableStatement?
con.createStatement()con.prepareStatement()con.prepareCall()con.callStatement()
Answer: C) con.prepareCall() -> Explanation: con.prepareCall("{call procedureName()}") is used to create a CallableStatement for calling stored procedures.
Q33. Which symbol is used for parameter placeholders in PreparedStatement?
?#@
Answer: B) ? -> Explanation: The ? symbol is used as a parameter placeholder in PreparedStatement. Example: SELECT * FROM student WHERE id=?.
ResultSet Processing
Q34. Which method retrieves a string column value from ResultSet?
getString()getText()getVarchar()getChar()
Answer: A) getString() -> Explanation: getString() retrieves a string column value from ResultSet. It can take either a column name or a column index.
Q35. Which method retrieves an integer column value from ResultSet?
getNumber()getInt()getInteger()getValue()
Answer: B) getInt() -> Explanation: getInt() retrieves an integer column value from ResultSet. Example: rs.getInt("id") or rs.getInt(1).
Q36. Which method moves the ResultSet cursor to the first row?
first()next()start()begin()
Answer: A) first() -> Explanation: first() moves the ResultSet cursor to the first row. next() moves forward one row at a time.
Q37. Which method moves the ResultSet cursor to the last row?
end()last()final()bottom()
Answer: B) last() -> Explanation: last() moves the ResultSet cursor to the last row. It requires a scrollable ResultSet.
Q38. Which method updates the current row in an updatable ResultSet?
updateRow()setRow()modifyRow()changeRow()
Answer: A) updateRow() -> Explanation: updateRow() updates the current row in an updatable ResultSet. It is called after updateString() or similar methods.
Metadata Management
Q39. Which interface provides information about the database?
ResultSetMetaDataDatabaseMetaDataParameterMetaDataConnectionMetaData
Answer: B) DatabaseMetaData -> Explanation: DatabaseMetaData provides information about the database and DBMS, such as product name, version, and supported features.
Q40. Which interface provides information about query result columns?
DatabaseMetaDataResultSetMetaDataColumnMetaDataQueryMetaData
Answer: B) ResultSetMetaData -> Explanation: ResultSetMetaData provides information about columns returned by a query, such as column names, data types, and column count.
Q41. Which method returns the number of columns in a ResultSet?
getColumnCount()getColumnNumber()columnCount()countColumns()
Answer: A) getColumnCount() -> Explanation: getColumnCount() returns the number of columns in a ResultSet. It is a method of ResultSetMetaData.
Q42. Which method returns the column name in ResultSetMetaData?
getColumnName(i)getColumn(i)getName(i)columnName(i)
Answer: A) getColumnName(i) -> Explanation: getColumnName(i) returns the name of the column at index i in ResultSetMetaData. Column indices start at 1.
Transactions and Batch Processing
Q43. What does ACID stand for in transaction processing?
- Atomicity, Consistency, Isolation, Durability
- Atomicity, Concurrency, Isolation, Durability
- Access, Consistency, Integrity, Durability
- Atomicity, Consistency, Integrity, Data
Answer: A) Atomicity, Consistency, Isolation, Durability -> Explanation: ACID stands for Atomicity, Consistency, Isolation, and Durability. These are the four properties that guarantee reliable transaction processing.
Q44. Which method saves transaction changes permanently?
save()commit()rollback()persist()
Answer: B) commit() -> Explanation: commit() saves transaction changes permanently to the database. It is called after successful execution of all statements in a transaction.
Q45. Which method undoes transaction changes?
undo()revert()rollback()cancel()
Answer: C) rollback() -> Explanation: rollback() undoes transaction changes, restoring the database to its previous state. It is used when an error occurs during a transaction.
Q46. Which method creates a partial rollback point?
setSavepoint()createSavepoint()addSavepoint()markSavepoint()
Answer: A) setSavepoint() -> Explanation: setSavepoint() creates a savepoint, which is a partial rollback point within a transaction. You can roll back to this point without undoing the entire transaction.
Q47. Which method adds a SQL statement to a batch?
addBatch()addStatement()batchAdd()insertBatch()
Answer: A) addBatch() -> Explanation: addBatch() adds a SQL statement to a batch. Multiple statements can be executed together using executeBatch().
Q48. Which method executes all statements in a batch?
runBatch()executeBatch()batchExecute()runAll()
Answer: B) executeBatch() -> Explanation: executeBatch() executes all statements added to the batch. It returns an int array with the update counts for each statement.
Best Practices
Q49. Which technique prevents SQL injection?
- Using Statement
- Using PreparedStatement
- Using CallableStatement
- Using DriverManager
Answer: B) Using PreparedStatement -> Explanation: PreparedStatement prevents SQL injection because parameters are escaped and treated as data, not as executable SQL code.
Q50. Which Java 7+ feature automatically closes resources?
- try-catch
- try-with-resources
- finally block
- auto-close
Answer: B) try-with-resources -> Explanation: try-with-resources is a Java 7+ feature that automatically closes resources (Connection, Statement, ResultSet) when the try block exits, even if an exception occurs.
SECTION B: THEORY QUESTIONS (20)
Q1. Define JDBC. Explain its need and advantages.
Answer:
Definition:JDBC (Java Database Connectivity) is a Java API that allows Java applications to connect to databases, execute SQL queries, and process results. It acts as a bridge between Java applications and databases.
JDBC Workflow:
Java Application → JDBC → JDBC Driver → DatabaseNeed for JDBC: Before JDBC, each database had its own API, and programs were database-dependent. Changing databases required rewriting code. JDBC solved this by providing:
- A standard API for all databases
- Database independence
- Easy database access
- SQL execution support
Advantages of JDBC:
| # | Advantage | Explanation |
|---|---|---|
| 1 | Platform Independent | Works on all Java-supported platforms |
| 2 | Database Independent | Can connect to multiple databases |
| 3 | Standard API | Same coding approach for different databases |
| 4 | Secure | Supports authentication and authorization |
| 5 | Easy SQL Execution | Supports SELECT, INSERT, UPDATE, DELETE |
Real-Time Example: A banking application uses JDBC to retrieve account details and update balances securely.
Q2. Explain the JDBC architecture with a diagram.
Answer:
JDBC Architecture:
┌──────────────────┐
│ Java Application │
└────────┬─────────┘
↓
┌──────────────────┐
│ JDBC API │
└────────┬─────────┘
↓
┌──────────────────┐
│ DriverManager │
└────────┬─────────┘
↓
┌──────────────────┐
│ JDBC Driver │
└────────┬─────────┘
↓
┌──────────────────┐
│ Database │
│ (MySQL, Oracle) │
└──────────────────┘Components:
| Component | Purpose |
|---|---|
| Java Application | The program that needs database access |
| JDBC API | Interfaces and classes for database operations |
| DriverManager | Manages JDBC drivers and creates connections |
| JDBC Driver | Translates JDBC calls into database-specific calls |
| Database | The actual data store |
Explanation:
- The Java application calls JDBC API methods.
- DriverManager selects the appropriate driver.
- The JDBC driver translates calls into database-specific calls.
- The database executes the operations and returns results.
- Results flow back through the driver to the application.
Q3. Explain the four types of JDBC drivers with their advantages and disadvantages.
Answer:
| Driver Type | Name | Architecture | Advantages | Disadvantages |
|---|---|---|---|---|
| Type 1 | JDBC-ODBC Bridge | Java → JDBC → ODBC → Database | Easy setup; connects to any ODBC database | Platform dependent; slow; ODBC required; removed after Java 8 |
| Type 2 | Native API Driver | Java → Native Driver → Database | Faster than Type 1 | Requires native installation; platform dependent |
| Type 3 | Network Protocol Driver | Java → Middleware → Database | Database independent; no client installation | Additional server required; extra network hop |
| Type 4 | Thin Driver (Pure Java) | Java → Database | Fastest; pure Java; portable; most used | Database-specific driver required |
Driver Comparison:
| Driver | Speed | Platform Independent | Client Installation |
|---|---|---|---|
| Type 1 | Slow | No | ODBC required |
| Type 2 | Medium | No | Native libraries |
| Type 3 | Fast | Yes | Middleware server |
| Type 4 | Fastest | Yes | None |
Example — Type 4:
Class.forName("com.mysql.cj.jdbc.Driver");Q4. Explain the five steps of the JDBC process with examples.
Answer:
Five Steps of JDBC:
1. Load Driver → 2. Establish Connection → 3. Execute Query → 4. Process Result → 5. Close ResourcesStep 1: Load Driver
Class.forName("com.mysql.cj.jdbc.Driver");Loads the JDBC driver class into memory.
Step 2: Establish Connection
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test",
"root",
"root"
);Step 3: Execute Query
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM student");Step 4: Process Result
while (rs.next()) {
System.out.println(rs.getString("name"));
}Step 5: Close Resources
rs.close();
stmt.close();
con.close();Complete Program:
import java.sql.*;
public class JdbcExample {
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root", "root");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
while (rs.next()) {
System.out.println(rs.getString("name"));
}
con.close();
}
}Q5. Explain the JDBC packages and their important interfaces and classes.
Answer:
JDBC Packages:
| Package | Purpose |
|---|---|
java.sql | Core JDBC classes and interfaces |
javax.sql | Advanced JDBC features (connection pooling, RowSet, DataSource) |
Important Interfaces:
| Interface | Purpose | Example |
|---|---|---|
Connection | Represents database connection | Connection con; |
Statement | Executes simple SQL queries | Statement stmt; |
PreparedStatement | Precompiled SQL with parameters | PreparedStatement ps; |
CallableStatement | Calls stored procedures | CallableStatement cs; |
ResultSet | Stores query results | ResultSet rs; |
Important Classes:
| Class | Purpose |
|---|---|
DriverManager | Creates connections |
SQLException | Handles database exceptions |
Types | SQL type constants |
Example:
import java.sql.*;
Connection con = DriverManager.getConnection(url, user, password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM student");javax.sql Example:
import javax.sql.DataSource;Q6. Explain the difference between Statement, PreparedStatement, and CallableStatement.
Answer:
| Aspect | Statement | PreparedStatement | CallableStatement |
|---|---|---|---|
| Purpose | Simple SQL queries | Precompiled SQL with parameters | Calls stored procedures |
| Creation | con.createStatement() | con.prepareStatement(sql) | con.prepareCall("{call proc()}") |
| Parameters | No parameters | Supports ? placeholders | Supports IN/OUT parameters |
| Performance | Slower for repeated execution | Faster (precompiled) | Fast (stored procedure) |
| SQL Injection | Vulnerable | Prevents SQL injection | Prevents SQL injection |
| Reusability | Not reusable | Reusable | Reusable |
| Use Case | Static queries | Dynamic queries with parameters | Complex business logic in DB |
Examples:
Statement:
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM student");PreparedStatement:
PreparedStatement ps = con.prepareStatement(
"SELECT * FROM student WHERE id=?");
ps.setInt(1, 101);
ResultSet rs = ps.executeQuery();CallableStatement:
CallableStatement cs = con.prepareCall("{call getStudents()}");
ResultSet rs = cs.executeQuery();Q7. Explain ResultSet processing in JDBC.
Answer:
ResultSet stores the results of a SQL query. It maintains a cursor pointing to the current row.
Retrieving Records:
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
while (rs.next()) {
System.out.println(rs.getString("name"));
}Cursor Navigation:
| Method | Purpose |
|---|---|
next() | Moves forward |
previous() | Moves backward |
first() | Moves to first row |
last() | Moves to last row |
absolute(n) | Moves to nth row |
relative(n) | Moves n rows from current |
Data Extraction:
| Method | Purpose |
|---|---|
getString("name") | Get string by column name |
getString(2) | Get string by column index |
getInt("id") | Get integer by column name |
getDate("dob") | Get date by column name |
Example:
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println(id + " " + name);
}Updating Records:
rs.absolute(1);
rs.updateString("name", "Amit");
rs.updateRow();Q8. Explain connection management in JDBC with best practices.
Answer:
Resource Handling: Always close resources after use.
rs.close();
stmt.close();
con.close();Using try-with-resources (Java 7+):
try (Connection con = DriverManager.getConnection(url, user, password)) {
// Use connection
} // Resources close automaticallyConnection Pooling:
Without Pooling:
Request → Create Connection → Execute Query → Close ConnectionWith Pooling:
Request → Connection Pool → DatabaseAdvantages of Connection Pooling:
- Faster performance
- Reduced overhead
- Better scalability
Performance Considerations:
| Technique | Benefit |
|---|---|
| PreparedStatement | Faster, prevents SQL injection |
| Close Resources | Avoids memory leaks |
| Connection Pooling | Improves application performance |
Best Practices:
- Use Type 4 Drivers
- Use PreparedStatement
- Close Connections
- Handle Exceptions
- Use Connection Pooling
Q9. Explain JDBC data types and type mapping.
Answer:
SQL Data Types:
| SQL Type | Example |
|---|---|
| INT | 101 |
| VARCHAR | Rahul |
| FLOAT | 95.5 |
| DATE | 2026-06-06 |
| BOOLEAN | TRUE |
Java Data Types:
| Java Type | Example |
|---|---|
| int | 101 |
| String | Rahul |
| float | 95.5f |
| Date | new Date() |
| boolean | true |
Type Mapping:
| SQL Type | Java Type |
|---|---|
| INT | int |
| BIGINT | long |
| FLOAT | float |
| DOUBLE | double |
| VARCHAR | String |
| DATE | java.sql.Date |
| TIME | java.sql.Time |
| TIMESTAMP | java.sql.Timestamp |
Examples:
int id = rs.getInt("id");
String name = rs.getString("name");
java.sql.Date d = rs.getDate("dob");Insert Date:
PreparedStatement ps = con.prepareStatement(
"INSERT INTO student VALUES(?)");
ps.setDate(1, java.sql.Date.valueOf("2026-06-06"));Q10. Explain metadata management in JDBC.
Answer:
Metadata means “data about data.” In JDBC, metadata provides information about the database structure, tables, columns, and query results.
Main Metadata Interfaces:
| Interface | Purpose |
|---|---|
DatabaseMetaData | Information about the database and DBMS |
ResultSetMetaData | Information about columns returned by a query |
ParameterMetaData | Information about parameters in a PreparedStatement |
ResultSetMetaData Example:
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
ResultSetMetaData meta = rs.getMetaData();
int columnCount = meta.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
System.out.println("Column: " + meta.getColumnName(i));
System.out.println("Type: " + meta.getColumnTypeName(i));
}DatabaseMetaData Example:
DatabaseMetaData dm = con.getMetaData();
System.out.println(dm.getDatabaseProductName());Output:
MySQLSchema Information:
DatabaseMetaData dm = con.getMetaData();
ResultSet tables = dm.getTables(null, null, "%", null);Applications:
- Dynamic Reports
- Database Analysis
- Admin Tools
- Data Migration
Q11. Explain transaction processing in JDBC with ACID properties.
Answer:
A transaction is a group of SQL operations executed as a single unit.
ACID Properties:
| Property | Meaning |
|---|---|
| Atomicity | All operations succeed or fail together |
| Consistency | Database remains valid |
| Isolation | Transactions execute independently |
| Durability | Changes remain permanent |
Commit Operations:
con.setAutoCommit(false);
stmt.executeUpdate(sql1);
stmt.executeUpdate(sql2);
con.commit();Rollback Operations:
try {
stmt.executeUpdate(sql);
con.commit();
} catch (Exception e) {
con.rollback();
}Savepoints:
stmt.executeUpdate(sql1);
Savepoint sp = con.setSavepoint();
stmt.executeUpdate(sql2);
con.rollback(sp); // Rolls back only sql2Benefits:
- Ensures data integrity
- Handles errors gracefully
- Supports partial rollback
Q12. Explain exception handling in JDBC.
Answer:
SQLException is the main exception class in JDBC. It is thrown when database operations fail.
Basic Handling:
try {
Connection con = DriverManager.getConnection(url, user, password);
// Database operations
} catch (SQLException e) {
System.out.println(e.getMessage());
}Error Codes:
catch (SQLException e) {
System.out.println(e.getErrorCode());
}Exception Chaining:
SQLException ex = e.getNextException();Debugging Techniques:
- Print SQL Query
- Check URL
- Verify Driver
- Verify Credentials
- Read Stack Trace
Example:
catch (SQLException e) {
e.printStackTrace();
}Best Practices:
- Catch specific exceptions
- Log errors properly
- Provide user-friendly messages
- Close resources in finally block
Q13. Explain batch processing in JDBC.
Answer:
Batch Processing executes multiple SQL statements together in one trip to the database.
Adding Statements to Batch:
Statement stmt = con.createStatement();
stmt.addBatch("INSERT INTO student VALUES(1,'A')");
stmt.addBatch("INSERT INTO student VALUES(2,'B')");Executing Batch:
int result[] = stmt.executeBatch();Complete Example:
Statement stmt = con.createStatement();
stmt.addBatch("INSERT INTO student VALUES(1,'Rahul')");
stmt.addBatch("INSERT INTO student VALUES(2,'Amit')");
stmt.executeBatch();Benefits:
- Fewer database calls
- Faster execution
- Better scalability
Practical Applications:
- Payroll Processing
- Student Result Upload
- Bulk Data Import
- Inventory Updates
Q14. Explain JDBC best practices.
Answer:
1. Secure Database Access: Use PreparedStatement to prevent SQL injection.
PreparedStatement ps = con.prepareStatement(
"SELECT * FROM user WHERE id=?");2. Resource Management: Always close resources.
rs.close();
stmt.close();
con.close();Better Approach — try-with-resources:
try (Connection con = DriverManager.getConnection(url, user, password)) {
// Use connection
}3. Performance Tuning:
| Technique | Benefit |
|---|---|
| Connection Pooling | Reduces connection creation overhead |
| Batch Processing | Improves bulk operation speed |
| PreparedStatement | Improves repeated query execution |
4. Coding Standards:
- Use meaningful variable names
- Handle exceptions properly
- Avoid hardcoded values
5. Use Type 4 Drivers: Fastest and most portable.
Q15. Explain the JDBC/ODBC bridge with its limitations.
Answer:
JDBC-ODBC Architecture:
Java Application → JDBC API → ODBC Driver → DatabaseBridge Configuration:
Step 1: Create ODBC Data Source Step 2: Register JDBC-ODBC Driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");Connectivity Process:
Java → JDBC → ODBC → DatabaseLimitations:
- Slow Performance — Extra translation layer
- Platform Dependent — Requires ODBC
- Requires ODBC Installation — Additional setup
- Removed in Java 8 — No longer supported
When to Use:
- Only for legacy systems
- Not recommended for modern applications
Q16. Explain the MySQL database integration with JDBC.
Answer:
MySQL Driver Setup:
Download MySQL Connector/J (JDBC driver for MySQL).
Common Driver Class:
com.mysql.cj.jdbc.DriverConnecting Java with MySQL:
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test",
"root",
"root"
);Database Operations:
| Operation | SQL | Method |
|---|---|---|
| Insert | INSERT INTO student VALUES(1,'Rahul') | executeUpdate() |
| Update | UPDATE student SET name='Amit' | executeUpdate() |
| Delete | DELETE FROM student | executeUpdate() |
| Select | SELECT * FROM student | executeQuery() |
Connection Testing:
if (con != null) {
System.out.println("Connection Successful");
}Output:
Connection SuccessfulQ17. Explain the difference between executeQuery(), executeUpdate(), and execute().
Answer:
| Method | Used For | Returns | Example |
|---|---|---|---|
executeQuery() | SELECT | ResultSet | stmt.executeQuery("SELECT * FROM student") |
executeUpdate() | INSERT, UPDATE, DELETE | int (affected rows) | stmt.executeUpdate("DELETE FROM student") |
execute() | Unknown query type | boolean | stmt.execute(sql) |
Examples:
executeQuery():
ResultSet rs = stmt.executeQuery("SELECT * FROM student");executeUpdate():
int rows = stmt.executeUpdate("DELETE FROM student");
System.out.println(rows + " rows affected");execute():
boolean result = stmt.execute(sql);
if (result) {
ResultSet rs = stmt.getResultSet();
} else {
int count = stmt.getUpdateCount();
}Q18. Explain the Connection interface in JDBC.
Answer:
The Connection interface represents an active connection with the database.
Obtaining a Connection:
Connection con = DriverManager.getConnection(url, user, password);Key Methods:
| Method | Purpose |
|---|---|
createStatement() | Creates a Statement |
prepareStatement(sql) | Creates a PreparedStatement |
prepareCall(sql) | Creates a CallableStatement |
setAutoCommit(bool) | Sets auto-commit mode |
commit() | Commits transaction |
rollback() | Rolls back transaction |
close() | Closes connection |
getMetaData() | Returns DatabaseMetaData |
Example:
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root", "root");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
con.close();Q19. Explain the ResultSetMetaData interface with an example.
Answer:
ResultSetMetaData provides information about the columns returned by a query.
Key Methods:
| Method | Purpose |
|---|---|
getColumnCount() | Number of columns |
getColumnName(i) | Column name at index i |
getColumnTypeName(i) | Data type at index i |
getColumnDisplaySize(i) | Display size |
isNullable(i) | Nullability |
Example:
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
ResultSetMetaData meta = rs.getMetaData();
int columnCount = meta.getColumnCount();
System.out.println("Number of columns: " + columnCount);
for (int i = 1; i <= columnCount; i++) {
System.out.println("Column: " + meta.getColumnName(i));
System.out.println("Type: " + meta.getColumnTypeName(i));
}Output:
Number of columns: 4
Column: id
Type: INT
Column: name
Type: VARCHAR
...Q20. Explain the complete JDBC program for student management.
Answer:
Complete Program:
import java.sql.*;
public class StudentManagement {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/school";
String user = "root";
String password = "root";
try {
// Step 1: Load Driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Step 2: Establish Connection
Connection con = DriverManager.getConnection(url, user, password);
// Step 3: Insert a student
PreparedStatement ps = con.prepareStatement(
"INSERT INTO student VALUES(?,?)");
ps.setInt(1, 101);
ps.setString(2, "Rahul");
ps.executeUpdate();
// Step 4: Retrieve students
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
while (rs.next()) {
System.out.println(
rs.getInt("id") + " " + rs.getString("name"));
}
// Step 5: Close Resources
rs.close();
stmt.close();
ps.close();
con.close();
} catch (ClassNotFoundException e) {
System.out.println("Driver not found.");
} catch (SQLException e) {
e.printStackTrace();
}
}
}Output:
101 RahulExplanation:
- Driver loaded with
Class.forName() - Connection established with
DriverManager.getConnection() - PreparedStatement used for safe insertion
- Statement used for retrieval
- All resources closed properly
SECTION C: ANALYTICAL QUESTIONS (10)
Q1. Analyze the following JDBC code and identify the errors.
import java.sql.*;
public class Test {
public static void main(String[] args) {
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost/test", "root", "root");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
System.out.println(rs.getString("name"));
}
}Answer:
Errors Identified:
- No driver loading:
Class.forName()is missing. The driver must be loaded before creating a connection. - No exception handling:
SQLExceptionandClassNotFoundExceptionare not handled. - ResultSet cursor not advanced:
rs.next()is not called beforers.getString(). The cursor starts before the first row. - Resources not closed:
rs,stmt, andconare not closed.
Corrected Code:
import java.sql.*;
public class Test {
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
try (Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost/test", "root", "root");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM student")) {
while (rs.next()) {
System.out.println(rs.getString("name"));
}
}
} catch (ClassNotFoundException e) {
System.out.println("Driver not found.");
} catch (SQLException e) {
e.printStackTrace();
}
}
}Q2. Analyze the following code and explain the output.
PreparedStatement ps = con.prepareStatement(
"SELECT * FROM student WHERE id=?");
ps.setInt(1, 101);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("name"));
}Answer:
Explanation:
- PreparedStatement Creation:
con.prepareStatement("SELECT * FROM student WHERE id=?")creates a precompiled SQL statement with a parameter placeholder?. - Parameter Setting:
ps.setInt(1, 101)sets the first parameter to 101. - Execution:
ps.executeQuery()executes the querySELECT * FROM student WHERE id=101. - Result Processing: The
while (rs.next())loop iterates through matching rows and prints thenamecolumn.
Output (if student with id=101 exists):
RahulKey Points:
- PreparedStatement prevents SQL injection
- Parameters are set by index (starting at 1)
executeQuery()returns a ResultSetrs.next()advances the cursor
Q3. Analyze the following transaction code and explain its behavior.
con.setAutoCommit(false);
try {
stmt.executeUpdate("UPDATE account SET balance=balance-1000 WHERE id=1");
stmt.executeUpdate("UPDATE account SET balance=balance+1000 WHERE id=2");
con.commit();
System.out.println("Transfer successful");
} catch (SQLException e) {
con.rollback();
System.out.println("Transfer failed");
}Answer:
Behavior:
- Auto-commit disabled:
con.setAutoCommit(false)disables automatic commit. - First update: Deducts 1000 from account 1.
- Second update: Adds 1000 to account 2.
- Commit:
con.commit()saves both changes permanently. - Exception handling: If any error occurs,
con.rollback()undoes both changes.
Output (success):
Transfer successfulOutput (failure):
Transfer failedKey Points:
- Ensures atomicity — both operations succeed or fail together
- Prevents partial transfers
- Uses ACID properties
- Essential for banking applications
Q4. Analyze the following metadata code and predict the output.
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
ResultSetMetaData meta = rs.getMetaData();
System.out.println("Columns: " + meta.getColumnCount());
for (int i = 1; i <= meta.getColumnCount(); i++) {
System.out.println(meta.getColumnName(i) + " - " + meta.getColumnTypeName(i));
}Answer:
Explanation:
rs.getMetaData()returns ResultSetMetaDatagetColumnCount()returns number of columnsgetColumnName(i)returns column namegetColumnTypeName(i)returns SQL data type
Output (for student table with id, name, age):
Columns: 3
id - INT
name - VARCHAR
age - INTKey Points:
- Metadata describes the result set structure
- Column indices start at 1
- Useful for dynamic reports
Q5. Analyze the following batch processing code.
Statement stmt = con.createStatement();
stmt.addBatch("INSERT INTO student VALUES(1,'A')");
stmt.addBatch("INSERT INTO student VALUES(2,'B')");
stmt.addBatch("INSERT INTO student VALUES(3,'C')");
int[] result = stmt.executeBatch();
System.out.println("Rows inserted: " + result.length);Answer:
Explanation:
- Three INSERT statements added to batch.
executeBatch()executes all three in one trip.resultarray contains update counts for each statement.result.length= 3 (three statements executed).
Output:
Rows inserted: 3Key Points:
- Batch processing reduces database round trips
- Improves performance for bulk operations
- Each statement’s result is in the array
- Used in payroll, inventory, and bulk imports
Q6. Analyze the following code and identify the SQL injection vulnerability.
String username = request.getParameter("username");
String password = request.getParameter("password");
Statement stmt = con.createStatement();
String sql = "SELECT * FROM users WHERE username='" + username +
"' AND password='" + password + "'";
ResultSet rs = stmt.executeQuery(sql);Answer:
Vulnerability:
If a user enters ' OR '1'='1 as username, the SQL becomes:
SELECT * FROM users WHERE username='' OR '1'='1' AND password='...'This bypasses authentication.
Corrected Code Using PreparedStatement:
String username = request.getParameter("username");
String password = request.getParameter("password");
PreparedStatement ps = con.prepareStatement(
"SELECT * FROM users WHERE username=? AND password=?");
ps.setString(1, username);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();Key Points:
- SQL Injection — inserting malicious SQL via user input
- PreparedStatement prevents it by escaping parameters
- Parameters are treated as data, not SQL code
- Always use PreparedStatement for user input
Q7. Analyze the following connection management code and suggest improvements.
Connection con = DriverManager.getConnection(url, user, password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
// ... process results ...
// No close() callsAnswer:
Issues:
- Resources not closed — memory leak
- No exception handling
- No try-with-resources
Improved Code:
try (Connection con = DriverManager.getConnection(url, user, password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM student")) {
while (rs.next()) {
System.out.println(rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
}Improvements:
- try-with-resources — auto-closes resources
- Exception handling — catches SQLException
- Cleaner code — no explicit close() calls
- Resource safety — closes even if exception occurs
Q8. Analyze the following driver comparison and select the best driver for a web application.
| Driver | Speed | Platform Independent | Client Installation |
|---|---|---|---|
| Type 1 | Slow | No | ODBC required |
| Type 2 | Medium | No | Native libraries |
| Type 3 | Fast | Yes | Middleware server |
| Type 4 | Fastest | Yes | None |
Answer:
Best Driver for Web Application: Type 4 (Thin Driver)
Justification:
- Fastest — Direct communication with database
- Platform Independent — Works on any platform
- No Client Installation — Pure Java, no native code
- Most Commonly Used — Industry standard
- Easy Deployment — No middleware server required
Example:
Class.forName("com.mysql.cj.jdbc.Driver");When to Use Others:
- Type 3: When database independence is critical and middleware is available
- Type 2: Legacy systems with native libraries
- Type 1: Only for testing, not production
Q9. Analyze the following code for a student management system and identify missing concepts.
public class StudentApp {
public static void main(String[] args) {
Connection con = DriverManager.getConnection(url, user, password);
Statement stmt = con.createStatement();
stmt.executeUpdate("INSERT INTO student VALUES(1,'Rahul')");
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
while (rs.next()) {
System.out.println(rs.getString("name"));
}
}
}Answer:
Missing Concepts:
- Driver loading:
Class.forName()is missing. - Exception handling: No try-catch for
SQLException. - Resource closing:
rs,stmt,conare not closed. - PreparedStatement: Should use PreparedStatement for INSERT.
- try-with-resources: Better resource management.
Improved Code:
import java.sql.*;
public class StudentApp {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/school";
String user = "root";
String password = "root";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
try (Connection con = DriverManager.getConnection(url, user, password);
PreparedStatement ps = con.prepareStatement(
"INSERT INTO student VALUES(?,?)");
Statement stmt = con.createStatement()) {
ps.setInt(1, 101);
ps.setString(2, "Rahul");
ps.executeUpdate();
try (ResultSet rs = stmt.executeQuery("SELECT * FROM student")) {
while (rs.next()) {
System.out.println(rs.getString("name"));
}
}
}
} catch (ClassNotFoundException e) {
System.out.println("Driver not found.");
} catch (SQLException e) {
e.printStackTrace();
}
}
}Key Improvements:
- Driver loaded
- Exception handling
- try-with-resources
- PreparedStatement for INSERT
- Proper resource closing
Q10. Design a complete JDBC program for a banking application that transfers money between accounts using transactions.
Answer:
Program:
import java.sql.*;
public class BankTransfer {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/bank";
String user = "root";
String password = "root";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
try (Connection con = DriverManager.getConnection(url, user, password)) {
con.setAutoCommit(false); // Start transaction
try {
// Deduct from sender
PreparedStatement debit = con.prepareStatement(
"UPDATE account SET balance=balance-? WHERE id=?");
debit.setDouble(1, 1000);
debit.setInt(2, 1);
debit.executeUpdate();
// Add to receiver
PreparedStatement credit = con.prepareStatement(
"UPDATE account SET balance=balance+? WHERE id=?");
credit.setDouble(1, 1000);
credit.setInt(2, 2);
credit.executeUpdate();
con.commit();
System.out.println("Transfer successful.");
} catch (SQLException e) {
con.rollback();
System.out.println("Transfer failed. Rolled back.");
e.printStackTrace();
}
}
} catch (ClassNotFoundException e) {
System.out.println("Driver not found.");
} catch (SQLException e) {
e.printStackTrace();
}
}
}Explanation:
| Step | Action |
|---|---|
| 1 | Load MySQL driver |
| 2 | Establish connection |
| 3 | Disable auto-commit |
| 4 | Deduct 1000 from account 1 |
| 5 | Add 1000 to account 2 |
| 6 | Commit transaction |
| 7 | On error, rollback |
Key Concepts:
- Atomicity: Both updates succeed or fail together
- Consistency: Total balance remains unchanged
- Isolation: Transaction is independent
- Durability: Changes persist after commit
Output (success):
Transfer successful.Output (failure):
Transfer failed. Rolled back.SUMMARY TABLE
| Section | Count | Topics Covered |
|---|---|---|
| MCQ | 50 | JDBC basics, drivers, packages, interfaces, process, PreparedStatement, ResultSet, metadata, transactions, batch, best practices |
| Theory | 20 | JDBC definition, architecture, drivers, process, packages, statements, ResultSet, connection management, data types, metadata, transactions, exceptions, batch, best practices, ODBC, MySQL, execute methods, Connection, ResultSetMetaData, complete program |
| Analytical | 10 | Code analysis, error identification, SQL injection, transaction design, driver selection, complete program design |