【问题标题】:Calling SQL server 2008 Stored Procedure from Java从 Java 调用 SQL Server 2008 存储过程
【发布时间】:2013-06-21 06:31:32
【问题描述】:

我在 SQL Server 2008 中创建了以下存储过程

Create PROCEDURE countInfected @infected int out
AS
Select @infected = COUNT(*) from userInfo where userID NOT IN (Select userID from deletedInfo);

我的java代码如下

CallableStatement infected = con.prepareCall("exec countInfected()");
infected.registerOutParameter(1, java.sql.Types.INTEGER);
infected.execute();
    System.out.println("Infected"+ infected.getInt(1));

但它会产生以下错误

core.dtable.Dbase.stored(Dbase.java:51) 处的 java.lang.NullPointerException

请指导我哪里错了

【问题讨论】:

  • 你的 SP 是 countNonInfected 并且你正在调用 countInfected。
  • 基本上我都有这两个过程,并且都有相同的代码,并且它们都产生相同的错误

标签: java sql-server sql-server-2008 jakarta-ee


【解决方案1】:
     try {
        conn     = DBConnection.SQLDB();
        conn.setAutoCommit(false) ;
        CallableStatement cs = null;
        cs = conn.prepareCall("{call dbo.xxCount(?)}");
        cs.registerOutParameter(1, java.sql.Types.INTEGER);
        cs.execute() ;
        System.out.println("INFECTED "+cs.getInt(1));
    }catch (Exception err){

在调用存储过程时输出参数。

【讨论】:

  • 感谢 rply elmer,我还没有使用任何 in 参数,dbo.xxCount(?)
  • 您是否尝试过将代码从 CallableStatement 更改为受感染 = con.prepareCall("exec countInfected()") ; to CallableStatement protected = con.prepareCall("exec countInfected(?)")
  • 是的,我都试过了,但在 cs.registerOutParameter(1, java.sql.Types.INTEGER); 上仍然出现问题;
【解决方案2】:

由于没有发布完整的代码,我假设 nonInfected.registerOutParameter(1, java.sql.Types.INTEGER); 是第 51 行。nonInfected 是调用给定过程所需的。

@infected 不用于 SQL 查询,如果它不只是输出类型参数而不是输入/输出。

尝试完全删除 nonInfected.registerOutParameter(1, java.sql.Types.INTEGER); 并运行。

【讨论】:

  • 抱歉打错了,我现在编辑一下,这段代码上面的连接已成功创建,其他记录集正在工作,但我对这些过程调用有问题。你有什么建议
  • 你为什么要两次Infected.registerOutParameter(1, java.sql.Types.INTEGER);
【解决方案3】:

我找到了解决办法,我只是在sql代码中添加一个语句

Create PROCEDURE countInfected @infected int out
AS
Select @infected = COUNT(*) from userInfo where userID NOT IN (Select userID from deletedInfo);
return @infected;

这对我有用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    • 1970-01-01
    • 2015-08-28
    • 1970-01-01
    • 2012-11-15
    相关资源
    最近更新 更多