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

18,076

Solution 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

Solution 2

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

Solution 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

Share:
18,076
Shavindra Manathunga
Author by

Shavindra Manathunga

I am not a professional programmer but I like and did many new inventions. Also I have lot more to go. In this journey I like to ask questions about things I don't know and I like to answer questions to give my little knowledge to everone.

Updated on June 14, 2022

Comments

  • Shavindra Manathunga
    Shavindra Manathunga almost 2 years

    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.