2082 9

BIT401 ยท 2082 ยท 5 marks

How do you handle multiple results in JDBC? Explain.

How do you handle multiple results in JDBC? Explain. [5]

Advanced Java ProgrammingChapter 5: Database Connectivity with JDBCHandling multiple result sets

Quick answer

Handling multiple results in JDBC involves managing situations where a single SQL statement execution returns more than one result set. This typically occurs with stored procedures or batch operations.

Handling Multiple Results in JDBC

Answer

Handling multiple results in JDBC involves managing situations where a single SQL statement execution returns more than one result set. This typically occurs with stored procedures or batch operations. Here's how to handle them:

1. Using execute() Method

The execute() method returns a boolean indicating whether the first result is a ResultSet:

Statement stmt = connection.createStatement();
boolean isResultSet = stmt.execute(sqlQuery);

if (isResultSet) {
    ResultSet rs = stmt.getResultSet();
    // Process first result set
} else {
    int updateCount = stmt.getUpdateCount();
    // Process update count
}

2. Processing Multiple Result Sets

Use getMoreResults() to move through subsequent result sets:

Statement stmt = connection.createStatement();
stmt.execute(sqlQuery);

int resultIndex = 0;
while (true) {
    ResultSet rs = stmt.getResultSet();
    if (rs != null) {
        // Process current result set
        while (rs.next()) {
            // Handle row data
        }
        resultIndex++;
    }
    
    // Move to next result
    if (!stmt.getMoreResults()) {
        break;
    }
}

3. Handling Update Counts

Distinguish between result sets and update counts:

int result = stmt.getUpdateCount();
if (result == -1) {
    // No more results
} else if (result == 0) {
    // Update/Insert/Delete executed
} else {
    // Number of rows affected
}

4. Key Methods

MethodPurpose
execute()Returns true if result is ResultSet, false if update count
getResultSet()Retrieves current ResultSet
getUpdateCount()Gets number of rows affected
getMoreResults()Moves to next result; returns true if ResultSet exists

5. Best Practice

Always close resources properly:

try {
    // Process multiple results
} finally {
    if (rs != null) rs.close();
    if (stmt != null) stmt.close();
}

This approach ensures efficient handling of complex SQL operations returning multiple result sets.

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.