Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get true or false using execute() in Java Statement [duplicate]

Tags:

java

execute

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.

like image 330
Shavindra Manathunga Avatar asked May 10 '26 09:05

Shavindra Manathunga


1 Answers

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

like image 170
Anderson Vieira Avatar answered May 13 '26 01:05

Anderson Vieira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!