3

I have Statement object called stmt, Connection object conn.

stmt = conn.createStatement();
boolean b = stmt.execute("INSERT INTO employee VALUES('E001', 'Smith')")

But this always produce false. I want true if above query executed successfully and false if the query fails executing. How can I achieve that result using execute() method.

5 Answers5

9

How can I achieve that result using execute() method.

You can't. It will only return true if the result has a ResultSet. If there is a problem with your insertion, the method will throw an exception. From the documentation:

boolean execute(String sql) throws SQLException

Returns:

true if the first result is a ResultSet object; false if it is an update count or there are no results

Throws:

SQLException - if a database access error occurs, this method is called on a closed Statement, the method is called on a PreparedStatement or CallableStatement

SQLTimeoutException - when the driver has determined that the timeout value that was specified by the setQueryTimeout method has been exceeded and has at least attempted to cancel the currently running Statement

Community
  • 1
  • 1
Anderson Vieira
  • 8,919
  • 2
  • 37
  • 48
2

Try using executeUpdate() method on the Statement. It should return you a int indicating the number of rows.

Yogesh_D
  • 17,656
  • 10
  • 41
  • 55
2

Statement.ececute() will return true if the first result is a ResultSet object, false if it is an update count or there are no results

You can use

int executeUpdate(String sql)

returns

1) the row count for SQL Data Manipulation Language (DML) statements or

2) 0 for SQL statements that return nothing

Docs

singhakash
  • 7,891
  • 6
  • 31
  • 65
0

You cant if it is not a select query.
This is what said in the doc

Returns:  
true if the first result is a ResultSet object; false if it is an update count or there are no results`.

You will get a result set when you give a select query not when insert or update, you will get false always in case of these type of query .
Now to make it sure if its run successfully or not i guess working with e Exceptions will help you

Using executeUpdate() will give you the row count so you can use that to predict.

Saif
  • 6,804
  • 8
  • 40
  • 61
0

You are doing an insert statement, If there is an resultset that has values returning from the execute statement there will be a result. Check the documentation

sathish_at_madison
  • 823
  • 11
  • 34