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

微笑、不失礼 提交于 2019-12-17 20:32:43

问题


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.


回答1:


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




回答2:


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




回答3:


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




回答4:


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.




回答5:


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



来源:https://stackoverflow.com/questions/29521554/how-to-get-true-or-false-using-execute-in-java-statement

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