In JDBC how does one know if the DDL statement was executed successfully?
Solution 1
A failing statement will always raise an SQLException
regardless of which method is used to execute it. executeUpdate
is suitable for any statement that cannot produce a ResultSet
, which makes it fit the bill perfectly for a DDL statement.
Solution 2
Unless you wrap the DDL in PL/QSL and catch the exception, it will bubble up to the JDBC call.
As far as which one to use, either one works fine, because for DDL you should ignore the return value anyway.
DDLs don't register as "row counts", unlike DML, so just use try/catch to catch failures, and assume in the absence of an exception, that it was successful.
Chiseled
Updated on June 26, 2022Comments
-
Chiseled almost 2 years
I am trying to execute a DDL statement on a Oracle 11g database using JDBC. I am doing it using the
boolean execute(String SQL)
of theStatement
class.Following is the code snippet that executes the query and tries to determine the result of the query:
// Create a SQL string String dropSql = "DROP TABLE Reviews"; stmt = conn.createStatement(); // Execute the query boolean result = stmt.execute(dropSql); // Get the result of the drop operation if(result) { // Its a result set System.out.println("Atleast one result set has been returned. Loop through them"); } else { // Its an update count or no result Integer updateCnt = stmt.getUpdateCount(); if(updateCnt == -1) { // No results System.out.println("No results returned by the query"); } else { // Update Count System.out.println("Update Count: " + updateCnt); } }
I am not a database guy, but is there a situation where the DDL statement would fail to execute and not raise a
SQLException
? If there isn't then I do not need to capture what the execute method returns. An absence ofSQLException
would indicate that the DDL statements executed successfully.The tutorial that I am following recommendeds the use of this method for DDL statements:
boolean execute(String SQL) : ....... Use this method to execute SQL DDL statements or when you need to use truly dynamic SQL.
While the Jdbc documentation recommends the use of
int executeUpdate(String sql)
for executing DDL statements. Which one is preferred among the two ?