I was trying to execute multiple lines of SQl using the Statement.execute() method like shown, and I tried to execute something that is obviously going to fail, but no exception is being thrown. Has anyone faced this issue in the past? What am I doing wrong?
Statement s = manager.createStatement();
boolean result = s.execute("CREATE TABLE table1(id int, value int, PRIMARY KEY (id));\n" +
"INSERT INTO table1 VALUES(1,10);\n" +
"INSERT INTO table1 VALUES(1,14);");
When I run this, everything looks fine, no error or exception anywhere.
I'm using the mssql-jdbc-9.2.0.jre8.jar
driver. Also tried with mssql-jdbc-12.2.0.jre8.jar
, no difference.
When I run the same thing using the .executeQuery() method, I get the expected exception regarding the violation of primary key.
3条答案
按热度按时间u7up0aaq1#
If you want to execute multiple queries, you can use batch method like this:
o4hqfura2#
The problem is that you're executing multiple statements, and that means that the SQL server implementation will report results per statement.
You will need to use the following to get exception from the second or third statement:
If there is a pending exception for the second (or in this case, third) statement, the call to
getMoreResults()
will throw it.Alternatively, use the JDBC API as it is intended to be used, and execute the statements individually.
ovfsdjhp3#
I think you should print out your Boolean result for execute execute(string) returns a Boolean which I believe will most likely be false!
The executeQuery(string) must return a "ResultSet", so it would throw exception because that is not the type of statement to use in executeQuery.
Any errors of SQL code execution belong to the SQL server, the Java only is reporting the outcome by particular tools it has to check the final outcome such as error code numbers, however, some interaction through the connector is monitored and will assert error as exception as the API docs generally define will occur with particular methods.