【问题标题】:Can't exec SQL stored procedure in java无法在java中执行SQL存储过程
【发布时间】:2023-03-30 03:32:01
【问题描述】:

我有一个 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

【问题讨论】:

  • 那么错误是什么?
  • JAVA 没有错误。但是存储不能在 SQL 中执行
  • 也许你只是错过了commit

标签: java sql stored-procedures


【解决方案1】:

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

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

cstmt.execute(); // MISSING!

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2020-11-19
      • 2010-11-02
      • 2010-12-16
      • 1970-01-01
      • 2012-07-02
      • 2016-10-11
      • 2018-06-22
      相关资源
      最近更新 更多