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

时光毁灭记忆、已成空白 提交于 2019-11-28 13:09:36

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

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

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

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.

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!