Mac Luc
Mac Luc

Reputation: 1001

Check if update query affected row or not

If I want to select stuff in my database I can just executeQuery in a ResultSet and return that to see what I got. But how do I do checks if I want to insert or update rows?
How can I see what the db returned? If it affected anything?

public static boolean doUpdate(String statement) {
    openConnection();
    try {
        stmt = conn.createStatement();
        stmt.executeUpdate(statement);
        closeConnection();
        return true;
    } catch (SQLException ex) {
        System.out.println(DBhandler.class.getName()+"\n"+ex);
        closeConnection();
    }
    return false;
}

I have tried to give the function a boolean return value, but the code in try will continue no matter if the update/insert worked or not.

Upvotes: 0

Views: 2212

Answers (2)

Alkis Kalogeris
Alkis Kalogeris

Reputation: 17745

The executeUpdate command returns the number of the affected rows. Keep that number and return true if at least one row was affected. Furthermore you should close your connection in a finally block, so even an exception occurs, the closeConnection() will be executed. Take a look at the below code.

public static boolean doUpdate(String statement) {
    boolean result = false;
    openConnection();
    try {
        stmt = conn.createStatement();
        result = stmt.executeUpdate(statement) > 0;
    } catch (SQLException ex) {
        System.out.println(DBhandler.class.getName()+"\n"+ex);
    } finally {
        closeConnection();
    }

    return result;
}

Upvotes: 2

rgettman
rgettman

Reputation: 178263

The executeUpdate method returns the number of rows affected for appropriate SQL statements executed.

Returns:

either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing

int rows = executeUpdate(statement);

Then you can look at rows to see if it's 0, and return a boolean appropriately.

Upvotes: 3

Related Questions