简体   繁体   English

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

[英]Can't exec SQL stored procedure in java

I have a stored procedure in SQL which can run in SQL without problems. 我在SQL中有一个存储过程,该存储过程可以在SQL中运行而不会出现问题。 But when I use Java to call it, the code can run but stored procedure cannot be called. 但是,当我使用Java调用它时,代码可以运行,但是无法调用存储过程。 Here's my code: 这是我的代码:

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;

}

And here is my stored procedure in SQL: 这是我在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

You need to call CallableStatement#execute() in your method. 您需要在您的方法中调用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 https://docs.oracle.com/javase/7/docs/api/java/sql/CallableStatement.html

Since CallableStatemnt is extending PreparedStatement,it inherited it's executing methods (execute, executeQuery, executeUpdate) to be executed like normal quires. 由于CallableStatemnt扩展了PreparedStatement,因此它继承了它的执行方法(execute,executeQuery,executeUpdate),使其像常规查询一样被执行。

I Would like to recommend using setQueryTimeout for any stored procedure calls to avoid timeout issues. 我想建议对任何存储过程调用使用setQueryTimeout以避免超时问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM