flash_love
flash_love
2018-02-01 13:59

java调用存储过程时的错误

5
  • 存储过程
public static int getNum(){
        Connection conn = null;
        CallableStatement cs =null;
        try {
            conn = JdbcUtils.getConnection();
            cs = conn.prepareCall("{call getNum(?)}");
            cs.registerOutParameter(1, Types.INTEGER);
            cs.execute();
            int num = cs.getInt(1);
            return num;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(cs!=null){
                    cs.close(); 
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            JdbcUtils.free(null, null, conn);
        }

        return 0;
    }

这样写总是返回0,如果改成下面那样就对了,这是为什么

    Connection conn = null;
        CallableStatement cs =null;
        try {
            conn = JdbcUtils.getConnection();
            cs = conn.prepareCall("{call getNum(?)}");
            cs.registerOutParameter(1, Types.INTEGER);
            ResultSet result=cs.executeQuery();
            int num = 0;
            if(result.next()){
                num = result.getInt("num");
            }
            return num;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(cs!=null){
                    cs.close(); 
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            JdbcUtils.free(null, null, conn);
        }

        return 0;
    }

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

6条回答