Exemplo n.º 1
1
 public ArrayList<DetalleFactura> buscar(Factura entidad) throws Exception {
   ArrayList<DetalleFactura> lista = new ArrayList<DetalleFactura>();
   try {
     cnn = Conexion.getConexion();
     CallableStatement cs = null;
     cs = cnn.prepareCall("call uspListDetalleFactrua(?)");
     cs.setInt(1, entidad.getIdFactura());
     rs = cs.executeQuery();
     while (rs.next()) {
       DetalleFactura objeto = new DetalleFactura();
       objeto.setIdDetalleFactura(rs.getInt("Iddetallefactura"));
       objeto.setIdProducto(rs.getInt("Idproducto"));
       objeto.setCantidad(rs.getInt("Cantidad"));
       objeto.setPrecio(rs.getDouble("Precio"));
       objeto.setSubTotal(rs.getDouble("Subtotal"));
       objeto.setIdFactura(rs.getInt("Idfactura"));
       objeto.setDProducto(rs.getString("DProducto"));
       lista.add(objeto);
     }
     cnn.close();
     cs.close();
   } catch (SQLException ex) {
     throw ex;
   }
   return lista;
 }
Exemplo n.º 2
1
	/**
	 * 获取游戏接口参数
	 * 
	 * @param id 
	 *        游戏接口参数编号
	 * @return 游戏接口参数
     */
	public wh.game.model.GameInterfaceParams get(int id) throws Exception{
		wh.game.model.GameInterfaceParams model = null;
		Map<String, Object> inParameters = new HashMap<String, Object>();
		inParameters.put("GameInterfaceParamsId", id);
		
		OutParameters outParameters = new OutParameters();
		outParameters.putOutParmType("ErrNo", java.sql.Types.INTEGER);
		outParameters.putOutParmType("ErrMsg", java.sql.Types.NVARCHAR);
        
		ResultSet rs = null;
		CallableStatement cstmt = null;
		int errNo = 0;
		String errMsg = "";
		try {
			rs = SQLHelper.runProcedure(Config.CONNECTION_STRING_ULD, "{call WH_Game_GameInterfaceParams_Get(?,?,?)}", inParameters, outParameters);
			if (rs != null) {
				rs.next();
				model = getModel(rs);
				
				cstmt = (CallableStatement)rs.getStatement();
				errNo = cstmt.getInt("ErrNo");
				errMsg = cstmt.getString("ErrMsg");
			}
		} catch (Exception e) {
			throw new Exception(e.getMessage(), e);
		} finally{
			SQLHelper.closeAll(cstmt);
		}
		
		MyErr.checkErr(errNo, errMsg);
		return model;
	}
Exemplo n.º 3
0
 /** Test batched callable statements where the call has no parameters. */
 public void testCallStmtNoParams() throws Exception {
   dropProcedure("jTDS_PROC");
   try {
     Statement stmt = con.createStatement();
     stmt.execute("create table #testbatch (id numeric(10) identity, data varchar(255))");
     stmt.execute(
         "create proc jTDS_PROC  as " + "INSERT INTO #testbatch (data) VALUES ('same each time')");
     CallableStatement cstmt = con.prepareCall("{call jTDS_PROC}");
     for (int i = 0; i < 5; i++) {
       cstmt.addBatch();
     }
     int x[];
     try {
       x = cstmt.executeBatch();
     } catch (BatchUpdateException e) {
       x = e.getUpdateCounts();
     }
     assertEquals(5, x.length);
     assertEquals(1, x[0]);
     assertEquals(1, x[1]);
     assertEquals(1, x[2]);
     assertEquals(1, x[3]);
     assertEquals(1, x[4]);
   } finally {
     dropProcedure("jTDS_PROC");
   }
 }
Exemplo n.º 4
0
 /**
  * Function to create temp visit dimension table using stored proc.
  *
  * @param tempTableName
  * @throws Exception
  */
 public void createTempTable(String tempEncounterMappingTableName) throws I2B2Exception {
   Connection conn = null;
   try {
     // smuniraju: Postgres requires only the IN arguments to be supplied in the call to proc.
     // CallableStatement callStmt = conn.prepareCall("{call "+ getDbSchemaName() +
     // "CREATE_TEMP_EID_TABLE(?,?)}");
     String prepareCallString = "";
     if (dataSourceLookup.getServerType().equalsIgnoreCase(DataSourceLookupDAOFactory.POSTGRES)) {
       prepareCallString = "{call " + getDbSchemaName() + "CREATE_TEMP_EID_TABLE(?)}";
     } else {
       prepareCallString = "{call " + getDbSchemaName() + "CREATE_TEMP_EID_TABLE(?,?)}";
     }
     conn = getDataSource().getConnection();
     CallableStatement callStmt = conn.prepareCall(prepareCallString);
     callStmt.setString(1, tempEncounterMappingTableName);
     callStmt.registerOutParameter(2, java.sql.Types.VARCHAR);
     callStmt.execute();
     this.getSQLServerProcedureError(dataSourceLookup.getServerType(), callStmt, 2);
   } catch (SQLException sqlEx) {
     sqlEx.printStackTrace();
     throw new I2B2Exception("SQLException occured" + sqlEx.getMessage(), sqlEx);
   } catch (Exception ex) {
     ex.printStackTrace();
     throw new I2B2Exception("Exception occured" + ex.getMessage(), ex);
   } finally {
     if (conn != null) {
       try {
         conn.close();
       } catch (SQLException sqlEx) {
         sqlEx.printStackTrace();
         log.error("Error while closing connection", sqlEx);
       }
     }
   }
 }
Exemplo n.º 5
0
  public static void main(String args[]) throws Exception {

    // Instantiate our DAO and get connection
    Dao dao = new Dao();
    Connection conn = dao.getConnection();

    // Prepare a callable statement
    // NOTE:  Curly brackets aka braces are required for the call builder
    // to work correctly.  Otherwise it'll actually just treat it as a
    // PreparedStatement, which may or may not be what you want!
    String s1 = "{CALL ADD_SERVICE(?,?,?)}";
    CallableStatement cs = conn.prepareCall(s1);

    // Set variables the usual way
    cs.setString(1, "DUB");
    cs.setString(2, "EWR");
    cs.setString(3, "A380");

    // Execute it
    cs.execute();

    // Get the result set (as usual)
    ResultSet rs = cs.getResultSet();

    // Go to the first result (the only one!) which came from the SELECT
    // statement in the procedure.
    rs.next();

    // Print the flight number to the screen
    System.out.println("New flight number is " + rs.getInt("flightNumber"));
  }
Exemplo n.º 6
0
  public static void main(String[] args) {

    try {
      // 1.加载驱动
      Class.forName("oracle.jdbc.driver.OracleDriver");
      // 2.获取连接
      Connection connection =
          DriverManager.getConnection(
              "jdbc:oracle:thin:@127.0.0.1:1521:orcl", "SCOTT", "wcy675600920");
      // 3.创建CallableStatement
      CallableStatement cs = connection.prepareCall("{call wwss_pro3(?,?)}");
      // 4.给?赋值
      cs.setString(1, "9527");
      cs.setInt(2, 3000);
      // 5.执行
      cs.execute();
      // 6.关闭
      cs.close();
      connection.close();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 7
0
 public ResultSet getResultSet(CallableStatement ps) throws SQLException {
   boolean isResultSet = ps.execute();
   while (!isResultSet && ps.getUpdateCount() != -1) {
     isResultSet = ps.getMoreResults();
   }
   return ps.getResultSet();
 }
Exemplo n.º 8
0
  /**
   * Prepares the statement and registers the OUT/INOUT parameters (if any).
   *
   * @param rsType the value of to be created ResultSet type
   * @param rsConcur the value of the to be created ResultSet concurrency
   * @return CallableStatement
   * @throws SQLException
   */
  public CallableStatement prepareCall(PyObject rsType, PyObject rsConcur) throws SQLException {

    // prepare the statement
    CallableStatement statement = null;
    boolean normal = ((rsType == Py.None) && (rsConcur == Py.None));

    try {

      // build the full call syntax
      String sqlString = toSql();

      if (normal) {
        statement = cursor.connection.connection.prepareCall(sqlString);
      } else {
        int t = rsType.asInt();
        int c = rsConcur.asInt();

        statement = cursor.connection.connection.prepareCall(sqlString, t, c);
      }

      // prepare the OUT parameters
      registerOutParameters(statement);
    } catch (SQLException e) {
      if (statement != null) {
        try {
          statement.close();
        } catch (Exception ex) {
        }
      }

      throw e;
    }

    return statement;
  }
Exemplo n.º 9
0
  public static List<Usuario> buscarUsuarios() {
    ConnectionPool pool = ConnectionPool.getInstance();
    Connection connection = pool.getConnection();
    CallableStatement cs = null;
    ResultSet rs = null;
    try {
      List<Usuario> usuas = new ArrayList();
      cs = connection.prepareCall("{ call cajeroReporte() }");
      rs = cs.executeQuery();
      while (rs.next()) {
        Usuario usa =
            new Usuario(
                rs.getString("nombreUsuario"),
                rs.getString("apellidoPaterno"),
                rs.getInt("idUsuario"));

        usuas.add(usa);
      }
      return usuas;
    } catch (Exception ex) {
      ex.printStackTrace();
      return null;

    } finally {
      DBUtil.closeResultSet(rs);
      DBUtil.closeStatement(cs);
      pool.freeConnection(connection);
    }
  }
Exemplo n.º 10
0
 public Guia obtener(int id) throws Exception {
   Guia objeto = new Guia();
   try {
     cnn = Conexion.getConexion();
     CallableStatement cs = null;
     cs = cnn.prepareCall("call uspGetGuia(?)");
     cs.setInt(1, id);
     rs = cs.executeQuery();
     while (rs.next()) {
       objeto.setIdGuia(rs.getInt("Idguia"));
       objeto.setPeriodo(rs.getString("Periodo"));
       objeto.setNumero(rs.getString("Numero"));
       objeto.setFecha(rs.getString("Fecha"));
       objeto.setTipoCambio(rs.getDouble("Tipocambio"));
       objeto.setSerie(rs.getString("Serie"));
       objeto.setNumeroDocumento(rs.getString("Numerodocumento"));
       objeto.setIdTipoMovimiento(rs.getInt("Idtipomovimiento"));
       objeto.setReferencia(rs.getString("Referencia"));
       objeto.setIdOrdenProduccion(rs.getInt("Idordenproduccion"));
       objeto.setIdClienteProveedor(rs.getInt("Idclienteproveedor"));
       objeto.setIdAlmacen(rs.getInt("Idalmacen"));
       objeto.setObservaciones(rs.getString("Observaciones"));
       objeto.setDOrdenProduccion(rs.getString("DOrdenProduccion"));
       objeto.setDClienteProveedor(rs.getString("DClienteProveedor"));
     }
     cnn.close();
     cs.close();
   } catch (SQLException ex) {
     throw ex;
   }
   return objeto;
 }
Exemplo n.º 11
0
  // test: do we get an appropriate update count when using ?=call?
  private static void testUpdate(Connection conn) throws Throwable {
    System.out.println("==============================================");
    System.out.println("TESTING UPDATE COUNT");
    System.out.println("==============================================\n");

    Statement scp = conn.createStatement();

    scp.execute(
        "CREATE FUNCTION returnsIntegerP(P1 INT) RETURNS INTEGER "
            + "EXTERNAL NAME '"
            + CLASS_NAME
            + "returnsIntegerP'"
            + " NO SQL LANGUAGE JAVA PARAMETER STYLE JAVA");

    CallableStatement cs = conn.prepareCall("? = call returnsIntegerP(0)");
    cs.registerOutParameter(1, Types.INTEGER);
    try {
      int updCount = cs.executeUpdate();
      System.out.println("executeUpdate on ? = call returnsIntegerP returned " + updCount);
      System.out.println("getString(1) returned " + cs.getString(1));
    } catch (SQLException se) {
      System.out.println("cs.execute() got unexpected exception: " + se);
    }

    cs.close();
    scp.execute("DROP FUNCTION returnsIntegerP");
    scp.close();
  }
Exemplo n.º 12
0
 public ArrayList<TipoVenta> getListarBean(Connection cnx) throws UnknownException {
   try {
     DaoTipoVenta ado = new DaoTipoVenta(pm);
     ArrayList<Parametro> parametros = new ArrayList();
     ArrayList objetos = ado.getListarBean(parametros, cnx);
     ResultSet rs = (ResultSet) objetos.get(0);
     CallableStatement cst = (CallableStatement) objetos.get(1);
     ArrayList<TipoVenta> lista = new ArrayList();
     while (rs.next()) {
       TipoVenta bean = new TipoVenta();
       bean.setIdTipoVenta(rs.getString("codvta").trim());
       bean.setDescripcion(rs.getString("Nomvta").trim());
       bean.setCuenta(rs.getString("cuenta").trim());
       bean.setManejaStock(rs.getInt("msto"));
       bean.setCobroEnCaja(rs.getInt("cobcaj"));
       bean.setVersion(Long.parseLong("1"));
       lista.add(bean);
     }
     rs.close();
     cst.close();
     return lista;
   } catch (Exception ex) {
     Logger.getLogger(LogicTipoVenta.class.getName()).log(Level.SEVERE, null, ex);
     throw new UnknownException(ex.getMessage());
   }
 }
Exemplo n.º 13
0
  public FaqCategories selectById(int id) throws SQLException {
    try {
      connection = ConnectionFactory.getInstance().getConnection();
      cs = connection.prepareCall("{call faq_categories_FindByPK(?)}");

      cs.setInt(1, id);

      resultSet = cs.executeQuery();
      FaqCategories faqc = null;
      while (resultSet.next()) {
        faqc =
            new FaqCategories(
                resultSet.getInt("idFAQ_Categories"),
                resultSet.getInt("idLanguage"),
                resultSet.getString("category_name"),
                resultSet.getString("category_description"));
      }
      return faqc;
    } finally {
      if (resultSet != null) {
        resultSet.close();
      }
      if (cs != null) {
        cs.close();
      }
      if (connection != null) {
        connection.close();
      }
    }
  }
Exemplo n.º 14
0
  public ArrayList<FaqCategories> select() throws SQLException {
    try {
      connection = ConnectionFactory.getInstance().getConnection();
      cs = connection.prepareCall("{Call faq_categories_FindAll}");
      resultSet = cs.executeQuery();

      ArrayList<FaqCategories> list = new ArrayList<FaqCategories>();
      while (resultSet.next()) {
        FaqCategories faqc =
            new FaqCategories(
                resultSet.getInt("idFAQ_Categories"),
                resultSet.getInt("idLanguage"),
                resultSet.getString("categoy_name"),
                resultSet.getString("category_description"));
        list.add(faqc);
      }
      return list;
    } finally {
      if (resultSet != null) {
        resultSet.close();
      }
      if (cs != null) {
        cs.close();
      }
      if (connection != null) {
        connection.close();
      }
    }
  }
Exemplo n.º 15
0
  // ---------------combo para seleccionar el tipo d epersona
  public static List<TipoPersona> getCargarComboTipoPersona() {
    List<TipoPersona> arreglo = null;
    TipoPersona obj = null;
    Connection conexion = null;
    ResultSet rs = null;
    try {
      conexion = ControladorBD.darConexionBD();
      CallableStatement st = conexion.prepareCall("{call sp_combo_tipo_persona()}");
      rs = st.executeQuery();
      if (rs.next()) {
        arreglo = new ArrayList<TipoPersona>();
        do {
          obj = new TipoPersona();

          obj.setId_tipo_persona(rs.getInt("id_tipo_persona"));
          obj.setNombre(rs.getString("nombre"));

          arreglo.add(obj);
        } while (rs.next());
      }
      rs.close();
      st.close();
      conexion.close();
    } catch (Exception error) {
      System.out.println("Error en el metodo por: " + error.getMessage());
      error.printStackTrace();
    }

    return arreglo;
  }
Exemplo n.º 16
0
  public static List<Sucursal> buscarSucursales() {
    ConnectionPool pool = ConnectionPool.getInstance();
    Connection connection = pool.getConnection();
    CallableStatement cs = null;
    ResultSet rs = null;
    try {
      List<Sucursal> sucursales = new ArrayList();
      cs = connection.prepareCall("{ call listaSucursal() }");
      rs = cs.executeQuery();
      while (rs.next()) {
        Sucursal suc = new Sucursal(rs.getInt("idSucursal"), rs.getString("nombreSucursal"));

        sucursales.add(suc);
      }
      return sucursales;
    } catch (Exception ex) {
      ex.printStackTrace();
      return null;

    } finally {
      DBUtil.closeResultSet(rs);
      DBUtil.closeStatement(cs);
      pool.freeConnection(connection);
    }
  }
Exemplo n.º 17
0
  public static List<Pago> buscarPagos() {
    ConnectionPool pool = ConnectionPool.getInstance();
    Connection connection = pool.getConnection();
    CallableStatement cs = null;
    ResultSet rs = null;
    try {
      List<Pago> pagos = new ArrayList();
      cs = connection.prepareCall("{ call listaPago() }");
      rs = cs.executeQuery();
      while (rs.next()) {
        Pago pag = new Pago(rs.getInt("idMetodoPago"), rs.getString("nombreMetodoPago"));

        pagos.add(pag);
      }
      return pagos;
    } catch (Exception ex) {
      ex.printStackTrace();
      return null;

    } finally {
      DBUtil.closeResultSet(rs);
      DBUtil.closeStatement(cs);
      pool.freeConnection(connection);
    }
  }
Exemplo n.º 18
0
  @Override
  protected Boolean vDelRow(Connection conn, ArrayList curRow) throws Exception {
    ADelDialog d = new ADelDialog(null, true);
    d.addPar("Наименование", curRow.get(1).toString());
    d.addPar("Описание", curRow.get(2).toString());

    d.setTitleIcon(
        new javax.swing.ImageIcon(
            getClass().getResource("/tradeterminal/icons/TT_icons/32X32/typdel.png")));
    d.setVisible(true);
    d.dispose();

    if (d.getReturnStatus() == ADialog.RET_OK) {
      int id = Integer.parseInt(curRow.get(0).toString());

      CallableStatement proc = conn.prepareCall("{call rb_doc_types_delete(?)}");

      proc.setInt(1, id);
      proc.execute();
      proc.close();

      return true;
    } else {
      return false;
    }
  }
Exemplo n.º 19
0
  public static CallableStatement callPro2(
      String sql, String[] inparameters, Integer[] outparameters) {

    try {

      ct = getConnection();
      cs = ct.prepareCall(sql);
      if (inparameters != null) {
        for (int i = 0; i < inparameters.length; i++) {
          cs.setObject(i + 1, inparameters[i]);
        }
      }

      if (outparameters != null) {
        for (int i = 0; i < outparameters.length; i++) {
          cs.registerOutParameter(inparameters.length + 1 + i, outparameters[i]);
        }
      }

      cs.execute();
    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException(e.getMessage());
    } finally {

    }
    return cs;
  }
Exemplo n.º 20
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    org.owasp.benchmark.helpers.SeparateClassRequest scr =
        new org.owasp.benchmark.helpers.SeparateClassRequest(request);
    String param = scr.getTheValue("foo");

    String bar = "safe!";
    java.util.HashMap<String, Object> map13216 = new java.util.HashMap<String, Object>();
    map13216.put("keyA-13216", "a Value"); // put some stuff in the collection
    map13216.put("keyB-13216", param.toString()); // put it in a collection
    map13216.put("keyC", "another Value"); // put some stuff in the collection
    bar = (String) map13216.get("keyB-13216"); // get it back out

    String sql = "{call verifyUserPassword('foo','" + bar + "')}";

    try {
      java.sql.Connection connection =
          org.owasp.benchmark.helpers.DatabaseHelper.getSqlConnection();
      java.sql.CallableStatement statement = connection.prepareCall(sql);
      statement.execute();
    } catch (java.sql.SQLException e) {
      throw new ServletException(e);
    }
  }
Exemplo n.º 21
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    org.owasp.benchmark.helpers.SeparateClassRequest scr =
        new org.owasp.benchmark.helpers.SeparateClassRequest(request);
    String param = scr.getTheParameter("foo");

    String bar = new Test().doSomething(param);

    String sql = "{call verifyUserPassword('foo','" + bar + "')}";

    try {
      java.sql.Connection connection =
          org.owasp.benchmark.helpers.DatabaseHelper.getSqlConnection();
      java.sql.CallableStatement statement =
          connection.prepareCall(
              sql,
              java.sql.ResultSet.TYPE_FORWARD_ONLY,
              java.sql.ResultSet.CONCUR_READ_ONLY,
              java.sql.ResultSet.CLOSE_CURSORS_AT_COMMIT);
      statement.execute();
    } catch (java.sql.SQLException e) {
      throw new ServletException(e);
    }
  } // end doPost
Exemplo n.º 22
0
 /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   // / TODO Auto-generated method stub
   PrintWriter out = response.getWriter();
   String mail = request.getParameter("Correo");
   DBConnection ping = new DBConnection();
   Connection con = ping.makeConnection("root", "sharPedo319");
   String resp = null;
   try {
     CallableStatement stmnt = con.prepareCall("{call obtenerPProducto(?)}");
     stmnt.setString(1, mail);
     // resp = stmnt.getString(1);
     stmnt.executeUpdate();
     ResultSet rs = stmnt.getResultSet();
     while (rs.next()) {
       json.put("activo", rs.getString(1));
       json.put("imagen", rs.getString(2));
       json.put("nombre", rs.getString(3));
       json.put("ubicacionInt", rs.getString(4));
       // resp = resp.concat("\nActivo:" + rs.getString(1) + ", imagen:" + rs.getString(2) + ",
       // nombre:" + rs.getString(3) + ", ubicacionInt" + rs.getString(4));
     }
   } catch (SQLException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
     resp = e.getMessage();
   } catch (JSONException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } finally {
     ping.closeConnection();
   }
   out.print(resp);
   // doGet(request, response);
 }
Exemplo n.º 23
0
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String param = "";
    java.util.Enumeration<String> headerNames = request.getHeaderNames();
    if (headerNames.hasMoreElements()) {
      param = headerNames.nextElement(); // just grab first element
    }

    String bar = new Test().doSomething(param);

    String sql = "{call verifyUserPassword('foo','" + bar + "')}";

    try {
      java.sql.Connection connection =
          org.owasp.benchmark.helpers.DatabaseHelper.getSqlConnection();
      java.sql.CallableStatement statement =
          connection.prepareCall(
              sql,
              java.sql.ResultSet.TYPE_FORWARD_ONLY,
              java.sql.ResultSet.CONCUR_READ_ONLY,
              java.sql.ResultSet.CLOSE_CURSORS_AT_COMMIT);
      statement.execute();
    } catch (java.sql.SQLException e) {
      throw new ServletException(e);
    }
  } // end doPost
Exemplo n.º 24
0
  @Override
  void closeConnection(final Connection connection) throws SQLException {

    if (aggressiveCompact) {
      CallableStatement statement = null;
      try {
        LOCK.writeLock().lock();
        final java.util.Date start = new java.util.Date();
        LOGGER.trace("beginning shutdown compact");
        statement = dbConnection.prepareCall("SHUTDOWN COMPACT");
        statement.execute();
        LOGGER.trace(
            "completed shutdown compact in " + TimeDuration.fromCurrent(start).asCompactString());
      } catch (SQLException ex) {
        LOGGER.error("error during shutdown compact: " + ex.getMessage());
      } finally {
        close(statement);
        LOCK.writeLock().unlock();
      }
    }

    try {
      connection.close();
      if (driver != null) {
        DriverManager.deregisterDriver(driver);
        driver = null;
      }
    } catch (Exception e) {
      LOGGER.error("error during H2 shutdown: " + e.getMessage());
    }
  }
  /** Test of getDouble method, of inteface java.sql.CallableStatement. */
  public void testGetDouble() throws Exception {
    println("getDouble");

    if (!isTestOutParameters()) {
      return;
    }

    CallableStatement stmt;
    double expResult = 1D;
    double result = 0D;

    try {
      stmt = prepRegAndExec("{?= call cast(1 as double)}", 1, Types.DOUBLE);

      result = stmt.getDouble(1);
    } catch (Exception ex) {
      fail(ex.getMessage());
    }

    assertEquals(expResult, result);

    try {
      stmt = prepRegAndExec("{?= call cast(1 as float)}", 1, Types.DOUBLE);

      result = stmt.getDouble(1);
    } catch (Exception ex) {
      fail(ex.getMessage());
    }

    assertEquals(expResult, result);
  }
Exemplo n.º 26
0
  @Override
  public ResultSet ExecuteSproc(String sprocName, String[] parameters, int[] returnColumnTypes)
      throws SQLException {
    if (_conn.isClosed()) {
      throw new SQLException("Connection was already closed");
    }

    try {

      String paramsList = "";

      int listSize = parameters.length;
      for (int i = 0; i < listSize; i++) {
        paramsList += parameters[i];
        if (i != listSize - 1) {
          paramsList += ", ";
        }
      }

      CallableStatement statement =
          _conn.prepareCall("{call " + sprocName + "(" + paramsList + ")}");

      for (int i = 0; i < returnColumnTypes.length; i++) {
        statement.registerOutParameter(i + 1, returnColumnTypes[i]);
      }

      return statement.executeQuery();
    } catch (SQLException ex) {
      throw ex;
    }
  }
  public boolean outStu(String stuId, String rmark) throws DataBaseException {

    Statement stmt;
    stmt = DB.CreateStatement();
    String sql = "select StuId from StuDormRoom where StuId='" + stuId + "'";
    try {
      ResultSet rs = stmt.executeQuery(sql);

      if (rs != null && !rs.next()) {
        return false;
      }

    } catch (SQLException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }

    try {
      CallableStatement cst = connection.prepareCall("{call proc_StuInOut_SDM_out(?,?)}");
      cst.setString(1, stuId);
      cst.setString(2, rmark);
      int r = cst.executeUpdate();
      cst.close();
      if (r > 0) {
        return true;
      } else {
        return false;
      }

    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return false;
    }
  }
Exemplo n.º 28
0
  public static List<Departamento> buscarDepartamentos() {
    ConnectionPool pool = ConnectionPool.getInstance();
    Connection connection = pool.getConnection();
    CallableStatement cs = null;
    ResultSet rs = null;
    try {
      List<Departamento> departamentos = new ArrayList();
      cs = connection.prepareCall("{ call listaDepartamento() }");
      rs = cs.executeQuery();
      while (rs.next()) {
        Departamento dpo =
            new Departamento(rs.getInt("idDepartamento"), rs.getString("nombreDepartamento"));

        departamentos.add(dpo);
      }
      return departamentos;
    } catch (Exception ex) {
      ex.printStackTrace();
      return null;

    } finally {
      DBUtil.closeResultSet(rs);
      DBUtil.closeStatement(cs);
      pool.freeConnection(connection);
    }
  }
Exemplo n.º 29
0
  /**
   * Descripción de Método
   *
   * @param ProcedureName
   * @return
   */
  private boolean startDBProcess(String ProcedureName) {

    // execute on this thread/connection

    log.fine(ProcedureName + "(" + m_pi.getAD_PInstance_ID() + ")");

    String sql = "{call " + ProcedureName + "(?)}";

    try {
      CallableStatement cstmt = DB.prepareCall(sql); // ro??

      cstmt.setInt(1, m_pi.getAD_PInstance_ID());
      cstmt.executeUpdate();
      cstmt.close();
    } catch (Exception e) {
      log.log(Level.SEVERE, sql, e);
      m_pi.setSummary(Msg.getMsg(Env.getCtx(), "ProcessRunError") + " " + e.getLocalizedMessage());
      m_pi.setError(true);

      return false;
    }

    // log.fine(Log.l4_Data, "ProcessCtl.startProcess - done");

    return true;
  } // startDBProcess
Exemplo n.º 30
0
  // ELIMINAR
  public String EliminarAsistenciaCurso(PublicacionesDTO escolaridaDTO) {
    try {
      try {
        ConexionBD conexionBD = new ConexionBD();
        conexionBD.abrir();
        Connection connection = conexionBD.getConexion();

        String sql = "{ ? = call eliminar_publicaciones(?)} ";
        CallableStatement callableStatement = connection.prepareCall(sql);
        callableStatement.registerOutParameter(1, Types.INTEGER);
        callableStatement.setInt(2, escolaridaDTO.getId());
        callableStatement.execute();
        Integer num = callableStatement.getInt(1);
        connection.close();
        if (num == 1) {
          return "¡Se elimino satisfactoriamente!";
        } else {
          return "";
        }

      } catch (Exception e) {
        e.printStackTrace();
      }
    } catch (Exception ex) {
      System.out.println("Error en.." + ex.getMessage());
    }

    return "";
  }