0

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.

AstroCB
  • 11,800
  • 20
  • 54
  • 68
Mac Luc
  • 925
  • 5
  • 14
  • 31
  • 2
    Doesn't [Statement.executeUpdate](http://docs.oracle.com/javase/8/docs/api/java/sql/Statement.html#executeUpdate-java.lang.String-) already return the number of affected rows by your update? – Edwin Dalorzo Sep 25 '14 at 18:03

2 Answers2

3

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.

Community
  • 1
  • 1
rgettman
  • 167,281
  • 27
  • 248
  • 326
2

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;
}
Barzev
  • 392
  • 2
  • 13
Alkis Kalogeris
  • 14,519
  • 11
  • 50
  • 98