Java获取输出CallableStatement JDBC

时间:2013-10-04 09:25:23

标签: java stored-procedures output

我是java的新手。我尝试在SQL SERVER中创建存储过程(SP)。 SP是:

go
create procedure sp_calculate
    @value1 int = 0,
    @value2 int = 0,
    @sum int OUTPUT,
    @multiply int OUTPUT
as
begin
    set nocount on
    set @sum = @value1 + @value2
    set @multiply = @value1 * @value2
end

我在Getting the Return Value from JDBC MSSQL之后制作了特征。所以我在Java下面这样做:

public static void main(String[] args) {
    try (Connection conn = ConnectionUtil.getConnection()) {
        CallableStatement cst = conn.prepareCall("{ (?, ?) = call sp_calculate ( @value1 =?, @value2=? ) }");

        cst.setInt(3, 4);//try some value
        cst.setInt(4, 10);//try some value

        cst.registerOutParameter(1, java.sql.Types.INTEGER);
        cst.registerOutParameter(2, java.sql.Types.INTEGER);
        cst.executeUpdate();
        int sum = cst.getInt(1);
        int multiply = cst.getInt(2);
        System.out.println("sum = " + sum + " - product = " + multiply);
    }
    catch (SQLException ex) {
        Logger.getLogger(StoredProcedured.class.getName()).log(Level.SEVERE, null, ex);
    }
}

但结果是"com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near '{'." 任何人都可以告诉我我创造了什么错误?

最后,我一直在努力:

public static void main(String[] args) {
    try (Connection conn = ConnectionUtil.getConnection()) {
        CallableStatement cst = conn.prepareCall("{ call sp_calculate ( ?,?,?,? ) }");

        cst.setInt(1, 10);//try some value
        cst.setInt(2, 4);//try some value

        cst.registerOutParameter(3, java.sql.Types.INTEGER);
        cst.registerOutParameter(4, java.sql.Types.INTEGER);
        cst.executeUpdate();
        int sum = cst.getInt(3);
        int product = cst.getInt(4);
        System.out.println("sum = " + sum + " - product = " + product);
    }
    catch (SQLException ex) {
        Logger.getLogger(StoredProcedured.class.getName()).log(Level.SEVERE, null, ex);
    }
}

1 个答案:

答案 0 :(得分:2)

尝试调用这样的程序:

String callableQuery = "{call sp_calculate(?, ?, ?, ?)}";

cst.setInt(1, 1); // IN parameter
cst.setInt(2, 4); // IN parameter

cst.registerOutParameter(3, java.sql.Types.INTEGER); // OUT parameter
cst.registerOutParameter(4, java.sql.Types.INTEGER); // OUT parameter