无法在 java 中执行 SQL 存储过程

Can't exec SQL stored procedure in java

我在 SQL 中有一个存储过程,它可以 运行 在 SQL 中没有问题。但是当我用Java调用的时候,代码可以运行但是存储过程调用不了。这是我的代码:

public int countPV(int value){
    Connection conn = null;
    ResultSet rs = null;

    try {
        conn = MyConection.getConnection();
        CallableStatement cstmt = conn.prepareCall("{call countPV(?)}");
        cstmt.setInt(1, value);
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    }finally{
        try {

            MyConection.closeConnection(conn, null, rs);
        } catch (Exception e) {
        }
    }
    return 1;

}

这是我在 SQL 中的存储过程:

CREATE procedure countPV (@pID int)
as
begin
WHILE (2>1)
BEGIN
    update tblUser
    set countx = countx + 1
    where ID = @pID
    SET @pID = (select parentID from tblUser where ID = @pID)
    if(@pID = (select parentID from tblUser where ID = @pID))
    break;
END
end

您需要在您的方法中调用CallableStatement#execute()

CallableStatement cstmt = conn.prepareCall("{call countPV(?)}");
cstmt.setInt(1, value);

cstmt.execute(); // MISSING!

https://docs.oracle.com/javase/7/docs/api/java/sql/CallableStatement.html

由于 CallableStatemnt 是对 PreparedStatement 的扩展,它继承了它的执行方法(execute、executeQuery、executeUpdate)以像普通查询一样执行。

我建议对任何存储过程调用使用 setQueryTimeout 以避免超时问题。