I was working on simple project which takes sql query from user and displays the results in JTable I want to determine if select statement was entered or any other DML/DDL statement was entered so I can call
executeUpdate() accordingly. I thought of checking the query if it begins with select. Is there a better way to do this.
Best How To :
Instead of trying to decide if you need to call
executeUpdate, you can just use
The javadoc of
Executes the given SQL statement, which may return multiple results. In some (uncommon) situations, a single SQL statement may return multiple result sets and/or update counts. Normally you can ignore this unless you are (1) executing a stored procedure that you know may return multiple results or (2) you are dynamically executing an unknown SQL string.
execute methods have a boolean return value which means:
false: first result is either an update count, or there are no results
true : first result is a result set
I am intentionally saying first result, as JDBC allows for a single statement having multiple results (eg a SQL Server stored procedure can return multiple result sets and update counts in any order).
false, you need to call
getUpdateCount. This either returns an update count (0 or higher), or
-1 to indicate there are no more results. As an aside: calling
getUpdateCount when the result was
true should also return
true, you need to call
getResultSet to obtain the result set.
To process more results (that is if you either just processed a result set or
getUpdateCount was not
-1), then you call
getMoreResults, which also returns a boolean, with the exact same meaning as above, etc.
This sounds complex, but most databases only support a single result set, and if you only care about a result set, then you only need to check if
true to then use
getResultset (or not if