for*_*ect 2 java sql-server stored-procedures jdbc
我正在使用准备好的语句 jdbc 模板运行存储过程:
conn = dbrm.getConnection(this.dataSources.get(aas.getArgumentValue("dataSource")));
Statement stmt = conn.createStatement();
try{
boolean hasResultSet = stmt.execute(query);
catch(Exception e){
// log and handle appropriately
}
Run Code Online (Sandbox Code Playgroud)
我的存储过程基本上是一个存储过程调用另外两个存储过程。
我遇到的问题是,如果存储过程的第一个语句之后出现异常,那么该异常不会返回到 jdbc 模板,因此看来我的存储过程适用于我的 java 代码,即使它没有这显然是有问题的。
有没有办法手动检查存储过程的输出或使所有可能的异常冒泡到java?
看起来,当执行存储过程时,引发的异常可能会“排队”在成功结果后面。为了“检索”异常,我们可能必须使用对象getMoreResults的方法CallableStatement。
例如,给定存储过程
CREATE PROCEDURE [dbo].[Table1sp] AS
BEGIN
SET NOCOUNT ON;
SELECT 123;
CREATE TABLE #Table1 (textcol VARCHAR(50) PRIMARY KEY);
INSERT INTO #Table1 (textcol) VALUES (NULL); -- error here
END
Run Code Online (Sandbox Code Playgroud)
如果我们运行 Java 代码
String connectionUrl = "jdbc:sqlserver://localhost:52865;"
+ "databaseName=myDb;" + "integratedSecurity=true";
try (Connection conn = DriverManager.getConnection(connectionUrl)) {
try (CallableStatement cs = conn.prepareCall("{call Table1sp}")) {
cs.execute();
ResultSet rs = cs.getResultSet();
rs.next();
System.out.println(rs.getInt(1));
rs.close();
}
} catch (Exception e) {
e.printStackTrace(System.err);
}
Run Code Online (Sandbox Code Playgroud)
然后我们只打印该值123,我们的代码就会继续执行,就好像没有任何错误一样。
但是,如果我们跟进电话getMoreResults()......
String connectionUrl = "jdbc:sqlserver://localhost:52865;"
+ "databaseName=myDb;" + "integratedSecurity=true";
try (Connection conn = DriverManager.getConnection(connectionUrl)) {
try (CallableStatement cs = conn.prepareCall("{call Table1sp}")) {
cs.execute();
ResultSet rs = cs.getResultSet();
rs.next();
System.out.println(rs.getInt(1));
rs.close();
try {
cs.getMoreResults();
} catch (com.microsoft.sqlserver.jdbc.SQLServerException ex) {
System.out.println("SQLServerException: " + ex.getMessage());
}
}
} catch (Exception e) {
e.printStackTrace(System.err);
}
Run Code Online (Sandbox Code Playgroud)
...然后异常被捕获:
123
SQLServerException: Cannot insert the value NULL into column 'textcol', table 'tempdb.dbo.#Table1 ...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2129 次 |
| 最近记录: |