BTCE | 5th Sem
Adv-Java SubjectUnit 3

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?

  1. Java Database Connectivity
  2. Java Data Control
  3. Java Dynamic Connection
  4. 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?

  1. java.db
  2. java.sql
  3. javax.jdbc
  4. java.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:

  1. Two Java applications
  2. Java applications and databases
  3. Two databases
  4. 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?

  1. Connection
  2. DriverManager
  3. Statement
  4. ResultSet

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?

  1. Platform independent
  2. Database independent
  3. Requires ODBC installation
  4. 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?

  1. Driver → JDBC → Application → Database
  2. Java Application → JDBC → JDBC Driver → Database
  3. Database → JDBC → Driver → Application
  4. 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?

  1. Type 1
  2. Type 2
  3. Type 3
  4. 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”?

  1. Type 1
  2. Type 2
  3. Type 3
  4. 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?

  1. Type 1
  2. Type 2
  3. Type 3
  4. 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?

  1. Type 1
  2. Type 2
  3. Type 3
  4. 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?

  1. Type 1
  2. Type 2
  3. Type 3
  4. 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?

  1. Type 1
  2. Type 2
  3. Type 3
  4. 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?

  1. Type 1 and Type 2
  2. Type 3 and Type 4
  3. Only Type 1
  4. 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?

  1. java.sql
  2. javax.sql
  3. java.jdbc
  4. javax.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?

  1. Statement
  2. ResultSet
  3. Connection
  4. DriverManager

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?

  1. Connection
  2. Statement
  3. ResultSet
  4. DriverManager

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?

  1. Statement
  2. Connection
  3. ResultSet
  4. DriverManager

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?

  1. SQLException
  2. IOException
  3. DatabaseException
  4. JDBCException

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?

  1. Statement
  2. PreparedStatement
  3. CallableStatement
  4. Connection

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?

  1. Establish connection
  2. Load driver
  3. Execute query
  4. 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?

  1. DriverManager.load()
  2. Class.forName()
  3. Connection.load()
  4. 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?

  1. DriverManager.getConnection()
  2. Connection.open()
  3. Driver.connect()
  4. 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?

  1. jdbc:mysql://host:port/database
  2. mysql:jdbc://host:port/database
  3. jdbc://mysql:host:port/database
  4. jdbc: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?

  1. 1521
  2. 3306
  3. 5432
  4. 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?

  1. executeUpdate()
  2. executeQuery()
  3. execute()
  4. 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?

  1. executeQuery()
  2. executeUpdate()
  3. execute()
  4. 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?

  1. Execute query
  2. Process result
  3. Close resources
  4. 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?

  1. next()
  2. previous()
  3. first()
  4. 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?

  1. A statement that is precompiled
  2. A statement that is executed once
  3. A statement that cannot accept parameters
  4. 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?

  1. setInt()
  2. setInteger()
  3. setNumber()
  4. 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?

  1. Slower execution
  2. Prevents SQL injection
  3. Cannot be reused
  4. 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?

  1. con.createStatement()
  2. con.prepareStatement()
  3. con.prepareCall()
  4. 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?

  1. ?
  2. #
  3. @

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?

  1. getString()
  2. getText()
  3. getVarchar()
  4. 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?

  1. getNumber()
  2. getInt()
  3. getInteger()
  4. 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?

  1. first()
  2. next()
  3. start()
  4. 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?

  1. end()
  2. last()
  3. final()
  4. 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?

  1. updateRow()
  2. setRow()
  3. modifyRow()
  4. 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?

  1. ResultSetMetaData
  2. DatabaseMetaData
  3. ParameterMetaData
  4. ConnectionMetaData

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?

  1. DatabaseMetaData
  2. ResultSetMetaData
  3. ColumnMetaData
  4. QueryMetaData

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?

  1. getColumnCount()
  2. getColumnNumber()
  3. columnCount()
  4. 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?

  1. getColumnName(i)
  2. getColumn(i)
  3. getName(i)
  4. 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?

  1. Atomicity, Consistency, Isolation, Durability
  2. Atomicity, Concurrency, Isolation, Durability
  3. Access, Consistency, Integrity, Durability
  4. 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?

  1. save()
  2. commit()
  3. rollback()
  4. 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?

  1. undo()
  2. revert()
  3. rollback()
  4. 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?

  1. setSavepoint()
  2. createSavepoint()
  3. addSavepoint()
  4. 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?

  1. addBatch()
  2. addStatement()
  3. batchAdd()
  4. 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?

  1. runBatch()
  2. executeBatch()
  3. batchExecute()
  4. 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?

  1. Using Statement
  2. Using PreparedStatement
  3. Using CallableStatement
  4. 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?

  1. try-catch
  2. try-with-resources
  3. finally block
  4. 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 → Database

Need 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:

  1. A standard API for all databases
  2. Database independence
  3. Easy database access
  4. SQL execution support

Advantages of JDBC:

#AdvantageExplanation
1Platform IndependentWorks on all Java-supported platforms
2Database IndependentCan connect to multiple databases
3Standard APISame coding approach for different databases
4SecureSupports authentication and authorization
5Easy SQL ExecutionSupports 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:

ComponentPurpose
Java ApplicationThe program that needs database access
JDBC APIInterfaces and classes for database operations
DriverManagerManages JDBC drivers and creates connections
JDBC DriverTranslates JDBC calls into database-specific calls
DatabaseThe actual data store

Explanation:

  1. The Java application calls JDBC API methods.
  2. DriverManager selects the appropriate driver.
  3. The JDBC driver translates calls into database-specific calls.
  4. The database executes the operations and returns results.
  5. Results flow back through the driver to the application.

Q3. Explain the four types of JDBC drivers with their advantages and disadvantages.

Answer:

Driver TypeNameArchitectureAdvantagesDisadvantages
Type 1JDBC-ODBC BridgeJava → JDBC → ODBC → DatabaseEasy setup; connects to any ODBC databasePlatform dependent; slow; ODBC required; removed after Java 8
Type 2Native API DriverJava → Native Driver → DatabaseFaster than Type 1Requires native installation; platform dependent
Type 3Network Protocol DriverJava → Middleware → DatabaseDatabase independent; no client installationAdditional server required; extra network hop
Type 4Thin Driver (Pure Java)Java → DatabaseFastest; pure Java; portable; most usedDatabase-specific driver required

Driver Comparison:

DriverSpeedPlatform IndependentClient Installation
Type 1SlowNoODBC required
Type 2MediumNoNative libraries
Type 3FastYesMiddleware server
Type 4FastestYesNone

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 Resources

Step 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:

PackagePurpose
java.sqlCore JDBC classes and interfaces
javax.sqlAdvanced JDBC features (connection pooling, RowSet, DataSource)

Important Interfaces:

InterfacePurposeExample
ConnectionRepresents database connectionConnection con;
StatementExecutes simple SQL queriesStatement stmt;
PreparedStatementPrecompiled SQL with parametersPreparedStatement ps;
CallableStatementCalls stored proceduresCallableStatement cs;
ResultSetStores query resultsResultSet rs;

Important Classes:

ClassPurpose
DriverManagerCreates connections
SQLExceptionHandles database exceptions
TypesSQL 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:

AspectStatementPreparedStatementCallableStatement
PurposeSimple SQL queriesPrecompiled SQL with parametersCalls stored procedures
Creationcon.createStatement()con.prepareStatement(sql)con.prepareCall("{call proc()}")
ParametersNo parametersSupports ? placeholdersSupports IN/OUT parameters
PerformanceSlower for repeated executionFaster (precompiled)Fast (stored procedure)
SQL InjectionVulnerablePrevents SQL injectionPrevents SQL injection
ReusabilityNot reusableReusableReusable
Use CaseStatic queriesDynamic queries with parametersComplex 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:

MethodPurpose
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:

MethodPurpose
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 automatically

Connection Pooling:

Without Pooling:

Request → Create Connection → Execute Query → Close Connection

With Pooling:

Request → Connection Pool → Database

Advantages of Connection Pooling:

  1. Faster performance
  2. Reduced overhead
  3. Better scalability

Performance Considerations:

TechniqueBenefit
PreparedStatementFaster, prevents SQL injection
Close ResourcesAvoids memory leaks
Connection PoolingImproves application performance

Best Practices:

  1. Use Type 4 Drivers
  2. Use PreparedStatement
  3. Close Connections
  4. Handle Exceptions
  5. Use Connection Pooling

Q9. Explain JDBC data types and type mapping.

Answer:

SQL Data Types:

SQL TypeExample
INT101
VARCHARRahul
FLOAT95.5
DATE2026-06-06
BOOLEANTRUE

Java Data Types:

Java TypeExample
int101
StringRahul
float95.5f
Datenew Date()
booleantrue

Type Mapping:

SQL TypeJava Type
INTint
BIGINTlong
FLOATfloat
DOUBLEdouble
VARCHARString
DATEjava.sql.Date
TIMEjava.sql.Time
TIMESTAMPjava.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:

InterfacePurpose
DatabaseMetaDataInformation about the database and DBMS
ResultSetMetaDataInformation about columns returned by a query
ParameterMetaDataInformation 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:

MySQL

Schema Information:

DatabaseMetaData dm = con.getMetaData();
ResultSet tables = dm.getTables(null, null, "%", null);

Applications:

  1. Dynamic Reports
  2. Database Analysis
  3. Admin Tools
  4. 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:

PropertyMeaning
AtomicityAll operations succeed or fail together
ConsistencyDatabase remains valid
IsolationTransactions execute independently
DurabilityChanges 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 sql2

Benefits:

  • 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:

  1. Print SQL Query
  2. Check URL
  3. Verify Driver
  4. Verify Credentials
  5. 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:

  1. Fewer database calls
  2. Faster execution
  3. Better scalability

Practical Applications:

  1. Payroll Processing
  2. Student Result Upload
  3. Bulk Data Import
  4. 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:

TechniqueBenefit
Connection PoolingReduces connection creation overhead
Batch ProcessingImproves bulk operation speed
PreparedStatementImproves 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 → Database

Bridge Configuration:

Step 1: Create ODBC Data Source Step 2: Register JDBC-ODBC Driver

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connectivity Process:

Java → JDBC → ODBC → Database

Limitations:

  1. Slow Performance — Extra translation layer
  2. Platform Dependent — Requires ODBC
  3. Requires ODBC Installation — Additional setup
  4. 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.Driver

Connecting Java with MySQL:

Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(
    "jdbc:mysql://localhost:3306/test",
    "root",
    "root"
);

Database Operations:

OperationSQLMethod
InsertINSERT INTO student VALUES(1,'Rahul')executeUpdate()
UpdateUPDATE student SET name='Amit'executeUpdate()
DeleteDELETE FROM studentexecuteUpdate()
SelectSELECT * FROM studentexecuteQuery()

Connection Testing:

if (con != null) {
    System.out.println("Connection Successful");
}

Output:

Connection Successful

Q17. Explain the difference between executeQuery(), executeUpdate(), and execute().

Answer:

MethodUsed ForReturnsExample
executeQuery()SELECTResultSetstmt.executeQuery("SELECT * FROM student")
executeUpdate()INSERT, UPDATE, DELETEint (affected rows)stmt.executeUpdate("DELETE FROM student")
execute()Unknown query typebooleanstmt.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:

MethodPurpose
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:

MethodPurpose
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 Rahul

Explanation:

  1. Driver loaded with Class.forName()
  2. Connection established with DriverManager.getConnection()
  3. PreparedStatement used for safe insertion
  4. Statement used for retrieval
  5. 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:

  1. No driver loading: Class.forName() is missing. The driver must be loaded before creating a connection.
  2. No exception handling: SQLException and ClassNotFoundException are not handled.
  3. ResultSet cursor not advanced: rs.next() is not called before rs.getString(). The cursor starts before the first row.
  4. Resources not closed: rs, stmt, and con are 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:

  1. PreparedStatement Creation: con.prepareStatement("SELECT * FROM student WHERE id=?") creates a precompiled SQL statement with a parameter placeholder ?.
  2. Parameter Setting: ps.setInt(1, 101) sets the first parameter to 101.
  3. Execution: ps.executeQuery() executes the query SELECT * FROM student WHERE id=101.
  4. Result Processing: The while (rs.next()) loop iterates through matching rows and prints the name column.

Output (if student with id=101 exists):

Rahul

Key Points:

  • PreparedStatement prevents SQL injection
  • Parameters are set by index (starting at 1)
  • executeQuery() returns a ResultSet
  • rs.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:

  1. Auto-commit disabled: con.setAutoCommit(false) disables automatic commit.
  2. First update: Deducts 1000 from account 1.
  3. Second update: Adds 1000 to account 2.
  4. Commit: con.commit() saves both changes permanently.
  5. Exception handling: If any error occurs, con.rollback() undoes both changes.

Output (success):

Transfer successful

Output (failure):

Transfer failed

Key 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 ResultSetMetaData
  • getColumnCount() returns number of columns
  • getColumnName(i) returns column name
  • getColumnTypeName(i) returns SQL data type

Output (for student table with id, name, age):

Columns: 3
id - INT
name - VARCHAR
age - INT

Key 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:

  1. Three INSERT statements added to batch.
  2. executeBatch() executes all three in one trip.
  3. result array contains update counts for each statement.
  4. result.length = 3 (three statements executed).

Output:

Rows inserted: 3

Key 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() calls

Answer:

Issues:

  1. Resources not closed — memory leak
  2. No exception handling
  3. 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:

  1. try-with-resources — auto-closes resources
  2. Exception handling — catches SQLException
  3. Cleaner code — no explicit close() calls
  4. Resource safety — closes even if exception occurs

Q8. Analyze the following driver comparison and select the best driver for a web application.

DriverSpeedPlatform IndependentClient Installation
Type 1SlowNoODBC required
Type 2MediumNoNative libraries
Type 3FastYesMiddleware server
Type 4FastestYesNone

Answer:

Best Driver for Web Application: Type 4 (Thin Driver)

Justification:

  1. Fastest — Direct communication with database
  2. Platform Independent — Works on any platform
  3. No Client Installation — Pure Java, no native code
  4. Most Commonly Used — Industry standard
  5. 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:

  1. Driver loading: Class.forName() is missing.
  2. Exception handling: No try-catch for SQLException.
  3. Resource closing: rs, stmt, con are not closed.
  4. PreparedStatement: Should use PreparedStatement for INSERT.
  5. 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:

StepAction
1Load MySQL driver
2Establish connection
3Disable auto-commit
4Deduct 1000 from account 1
5Add 1000 to account 2
6Commit transaction
7On 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

SectionCountTopics Covered
MCQ50JDBC basics, drivers, packages, interfaces, process, PreparedStatement, ResultSet, metadata, transactions, batch, best practices
Theory20JDBC 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
Analytical10Code analysis, error identification, SQL injection, transaction design, driver selection, complete program design

On this page