寫成存儲過程,然後用CallableStatement 調用

解决方案 »

  1.   

    private  static String getTitleSql(String startDate,
                                 String endDate) throws DAOException {
        DBconn db = null;
        String sql = null; //须返回的sql语句
        ResultSet rs = null;
        Connection con = null;
        CallableStatement call = null;
        try {
          db = new DBconn();
          con = db.getConnection();
          call = con.prepareCall("{call p_dtsgdttj_getsql_top(?,?,?,?)}"); //调用存储过程
          call.registerOutParameter(3, java.sql.Types.VARCHAR); //登记输出参数为字符串(out)
          call.registerOutParameter(4, java.sql.Types.INTEGER); //登记输出参数为数字(out)      call.setString(1, startDate); //为in参数赋值
          call.setString(2, endDate); //为in参数赋值
          rs = call.executeQuery(); //置入结果集中
          sql = call.getString(3); //取出字符串
        }
        catch (ConnectionException e) {
          throw new DAOException(e, "统计报表失败!");
        }
        catch (SQLException e) {
          throw new DAOException(e);
        }// 关闭数据库资源
        finally {
          if (rs != null) {
            try {
              rs.close(); //关闭结果集
            }
            catch (Exception e) {
              e.printStackTrace();
            }
          }
          if (call != null) {
            try {
              call.close();
            }
            catch (Exception e) {
              e.printStackTrace();
            }
          }      if (con != null) {
            try {
              con.close(); //关闭连接
            }
            catch (Exception e) {
              e.printStackTrace();
            }
          }
        }
        return sql;
      }