@Override
  public void delete(Integer deptno) {
    int updateCount_EMPs = 0;

    Connection con = null;
    PreparedStatement pstmt = null;

    try {

      Class.forName(driver);
      con = DriverManager.getConnection(url, userid, passwd);

      // 1●設定於 pstm.executeUpdate()之前
      con.setAutoCommit(false);

      // 先刪除員工
      pstmt = con.prepareStatement(DELETE_EMPs);
      pstmt.setInt(1, deptno);
      updateCount_EMPs = pstmt.executeUpdate();
      // 再刪除部門
      pstmt = con.prepareStatement(DELETE_DEPT);
      pstmt.setInt(1, deptno);
      pstmt.executeUpdate();

      // 2●設定於 pstm.executeUpdate()之後
      con.commit();
      con.setAutoCommit(true);
      System.out.println("刪除部門編號" + deptno + "時,共有員工" + updateCount_EMPs + "人同時被刪除");

      // Handle any driver errors
    } catch (ClassNotFoundException e) {
      throw new RuntimeException("Couldn't load database driver. " + e.getMessage());
      // Handle any SQL errors
    } catch (SQLException se) {
      if (con != null) {
        try {
          // 3●設定於當有exception發生時之catch區塊內
          con.rollback();
        } catch (SQLException excep) {
          throw new RuntimeException("rollback error occured. " + excep.getMessage());
        }
      }
      throw new RuntimeException("A database error occured. " + se.getMessage());
    } finally {
      if (pstmt != null) {
        try {
          pstmt.close();
        } catch (SQLException se) {
          se.printStackTrace(System.err);
        }
      }
      if (con != null) {
        try {
          con.close();
        } catch (Exception e) {
          e.printStackTrace(System.err);
        }
      }
    }
  }
  private void putUpdateStoredBlock(StoredBlock storedBlock, boolean wasUndoable)
      throws SQLException {
    try {
      PreparedStatement s =
          conn.get()
              .prepareStatement(
                  "INSERT INTO headers(hash, chainWork, height, header, wasUndoable)"
                      + " VALUES(?, ?, ?, ?, ?)");
      // We skip the first 4 bytes because (on prodnet) the minimum target has 4 0-bytes
      byte[] hashBytes = new byte[28];
      System.arraycopy(storedBlock.getHeader().getHash().getBytes(), 3, hashBytes, 0, 28);
      s.setBytes(1, hashBytes);
      s.setBytes(2, storedBlock.getChainWork().toByteArray());
      s.setInt(3, storedBlock.getHeight());
      s.setBytes(4, storedBlock.getHeader().unsafeRimbitSerialize());
      s.setBoolean(5, wasUndoable);
      s.executeUpdate();
      s.close();
    } catch (SQLException e) {
      // It is possible we try to add a duplicate StoredBlock if we upgraded
      // In that case, we just update the entry to mark it wasUndoable
      if (!(e.getSQLState().equals(POSTGRES_DUPLICATE_KEY_ERROR_CODE)) || !wasUndoable) throw e;

      PreparedStatement s =
          conn.get().prepareStatement("UPDATE headers SET wasUndoable=? WHERE hash=?");
      s.setBoolean(1, true);
      // We skip the first 4 bytes because (on prodnet) the minimum target has 4 0-bytes
      byte[] hashBytes = new byte[28];
      System.arraycopy(storedBlock.getHeader().getHash().getBytes(), 3, hashBytes, 0, 28);
      s.setBytes(2, hashBytes);
      s.executeUpdate();
      s.close();
    }
  }
Exemple #3
0
  private static Map saveSites(ExchSite3[] sites, int siteType, int sourceID, Connection c)
      throws SQLException {
    PreparedStatement insert = null;
    PreparedStatement delete = null;
    try {
      insert =
          c.prepareStatement(
              "insert into dat_customer_sites (site_id, site_type, source_id, internal_name, display_name) "
                  + "values (?, ?, ?, ?, ?)");
      delete = c.prepareStatement("delete from dat_customer_sites where site_id = ?");

      Map siteIDs = new HashMap(sites.length * 2 + 1);
      for (int i = 0; i < sites.length; i++) {
        ExchSite3 site = sites[i];

        int siteID = queryLookupSiteId(sourceID, site.getInternalName(), siteType, c);

        if (siteID == 0) {
          // if we couldn't find an existing siteID, grab the next one from the sequence
          siteID = getNextFromSequence("seq_site_id", c);
        } else {
          // if there is an existing siteID, delete it so we can insert the changes
          delete.setInt(1, siteID);
          int deleted = delete.executeUpdate();
          if (deleted != 1) {
            throw new SQLException("Delete for siteID " + siteID + " returned " + deleted);
          }
        }

        siteIDs.put(site.getInternalName(), siteID);
        insert.setInt(1, siteID);
        insert.setInt(2, siteType);
        insert.setInt(3, sourceID);
        insert.setString(
            4, DirectoryUtils.truncateString(site.getInternalName(), DB_SITE_INTERNALNAME_LENGTH));
        insert.setString(
            5, DirectoryUtils.truncateString(site.getDisplayName(), DB_SITE_DISPLAYNAME_LENGTH));
        insert.executeUpdate();
      }
      return siteIDs;
    } finally {
      if (delete != null) {
        delete.close();
      }
      if (insert != null) {
        insert.close();
      }
    }
  }
  /**
   * Test that <code>Clob.getCharacterStream(long,long)</code> works on CLOBs that are streamed from
   * store. (DERBY-2891)
   */
  public void testGetCharacterStreamLongOnLargeClob() throws Exception {
    getConnection().setAutoCommit(false);

    // create large (>32k) clob that can be read from store
    final int size = 33000;
    StringBuilder sb = new StringBuilder(size);
    for (int i = 0; i < size; i += 10) {
      sb.append("1234567890");
    }

    final int id = BlobClobTestSetup.getID();
    PreparedStatement ps =
        prepareStatement("insert into blobclob(id, clobdata) values (?,cast(? as clob))");
    ps.setInt(1, id);
    ps.setString(2, sb.toString());
    ps.executeUpdate();
    ps.close();

    Statement s = createStatement();
    ResultSet rs = s.executeQuery("select clobdata from blobclob where id = " + id);
    assertTrue(rs.next());
    Clob c = rs.getClob(1);

    // request a small region of the clob
    BufferedReader r = new BufferedReader(c.getCharacterStream(4L, 3L));
    assertEquals("456", r.readLine());

    r.close();
    c.free();
    rs.close();
    s.close();
    rollback();
  }
  public static int updateTableDocType(Connection conn, ConnectionProvider connectionProvider)
      throws ServletException {
    String strSql = "";
    strSql =
        strSql
            + "      update c_doctype set ad_table_id = 'D1A97202E832470285C9B1EB026D54E2'"
            + "      where docbasetype in ('ARR', 'APP')";

    int updateCount = 0;
    PreparedStatement st = null;

    try {
      st = connectionProvider.getPreparedStatement(conn, strSql);

      updateCount = st.executeUpdate();
    } catch (SQLException e) {
      log4j.error("SQL error in query: " + strSql + "Exception:" + e);
      throw new ServletException(
          "@CODE=" + Integer.toString(e.getErrorCode()) + "@" + e.getMessage());
    } catch (Exception ex) {
      log4j.error("Exception in query: " + strSql + "Exception:" + ex);
      throw new ServletException("@CODE=@" + ex.getMessage());
    } finally {
      try {
        connectionProvider.releaseTransactionalPreparedStatement(st);
      } catch (Exception ignore) {
        ignore.printStackTrace();
      }
    }
    return (updateCount);
  }
  public static int deleteTableAccess(Connection conn, ConnectionProvider connectionProvider)
      throws ServletException {
    String strSql = "";
    strSql =
        strSql
            + "      DELETE FROM ad_table_access"
            + "      WHERE ad_table_id = '4D8C3B3C31D1410DA046140C9F024D17'"
            + "        AND isreadonly = 'Y'"
            + "        AND isexclude = 'N'"
            + "        AND created <= (SELECT created FROM ad_tab WHERE ad_tab_id = 'FF8080812F213146012F2135BC25000E')";

    int updateCount = 0;
    PreparedStatement st = null;

    try {
      st = connectionProvider.getPreparedStatement(conn, strSql);

      updateCount = st.executeUpdate();
    } catch (SQLException e) {
      log4j.error("SQL error in query: " + strSql + "Exception:" + e);
      throw new ServletException(
          "@CODE=" + Integer.toString(e.getErrorCode()) + "@" + e.getMessage());
    } catch (Exception ex) {
      log4j.error("Exception in query: " + strSql + "Exception:" + ex);
      throw new ServletException("@CODE=@" + ex.getMessage());
    } finally {
      try {
        connectionProvider.releaseTransactionalPreparedStatement(st);
      } catch (Exception ignore) {
        ignore.printStackTrace();
      }
    }
    return (updateCount);
  }
  public int delete(ValueObject obj) throws SQLException {

    if ((obj instanceof PT_KICA_ERR_LOGEntity) == false) {
      throw new SQLException("DAO 에러(1): PT_KICA_ERR_LOG : delete() ");
    }
    PT_KICA_ERR_LOGEntity entity = (PT_KICA_ERR_LOGEntity) obj;

    Connection conn = null;
    PreparedStatement ps = null;
    int result = 0;

    StringBuffer sb = new StringBuffer();
    sb.append("delete from PT_KICA_ERR_LOG  where  1=1")
        .append(" and SEQ = ")
        .append(toDB(entity.getSEQ()));

    KJFLog.sql(sb.toString());

    try {

      conn = this.getConnection();
      ps = conn.prepareStatement(sb.toString());

      result = ps.executeUpdate();

    } catch (SQLException e) {
      throw e;
    } finally {
      if (ps != null) ps.close();
      this.release(conn);
    }

    return result;
  }
  public int update(ValueObject obj) throws SQLException {

    if ((obj instanceof PT_KICA_ERR_LOGEntity) == false) {
      throw new SQLException("DAO 에러(1): PT_KICA_ERR_LOG : update() ");
    }
    PT_KICA_ERR_LOGEntity entity = (PT_KICA_ERR_LOGEntity) obj;

    Connection conn = null;
    PreparedStatement ps = null;
    int result = 0;

    StringBuffer sb = new StringBuffer();
    sb.append("update PT_KICA_ERR_LOG  set ")
        .append("U_D_FLAG = ")
        .append(toDB(entity.getU_D_FLAG()))
        .append(",")
        .append("YYYYMMDD = ")
        .append(toDB(entity.getYYYYMMDD()))
        .append(",")
        .append("TRANSHOUR = ")
        .append(toDB(entity.getTRANSHOUR()))
        .append(",")
        .append("FILENAME = ")
        .append(toDB(entity.getFILENAME()))
        .append(",")
        .append("ERRLOG = ")
        .append(toDB(entity.getERRLOG()))
        .append(",")
        .append("RESULT_FLAG = ")
        .append(toDB(entity.getRESULT_FLAG()))
        .append(",")
        .append("UPD_DT = ")
        .append(toDB(entity.getUPD_DT()))
        .append(",")
        .append("INS_DT = ")
        .append(toDB(entity.getINS_DT()))
        .append(" where  1=1 ");

    sb.append(" and SEQ = ").append(toDB(entity.getSEQ()));

    KJFLog.sql(sb.toString());

    try {

      conn = this.getConnection();
      ps = conn.prepareStatement(sb.toString());

      int i = 1;

      result = ps.executeUpdate();

    } catch (SQLException e) {
      throw e;
    } finally {
      if (ps != null) ps.close();
      this.release(conn);
    }

    return result;
  }
 public void excluir(Oriundo oriundo) throws SQLException {
   Connection con =
       DriverManager.getConnection(
           new conexao().url,
           new conexao().config.getString("usuario"),
           new conexao().config.getString("senha"));
   PreparedStatement ps = null;
   String sqlExcluir = "DELETE FROM oriundo WHERE codigo=?";
   try {
     ps = con.prepareStatement(sqlExcluir);
     ps.setInt(1, oriundo.getCodigo());
     ps.executeUpdate();
     JOptionPane.showMessageDialog(
         null, "Ecluido Com Sucesso: ", "Mensagem do Sistema - Excluir", 1);
   } catch (NumberFormatException e) {
     JOptionPane.showMessageDialog(
         null, "NumberFormaterExeption Erro: " + e.getMessage(), "ClasseDAO Func.Excluir", 0);
     e.printStackTrace();
   } catch (NullPointerException e) {
     JOptionPane.showMessageDialog(
         null, "NullPointerException Erro: " + e.getMessage(), "ClasseDAO Func. Excluir", 0);
     e.printStackTrace();
   } catch (SQLException e) {
     JOptionPane.showMessageDialog(
         null, "SQLException Erro: " + e.getMessage(), "ClasseDAO Func. Excluir", 0);
     e.printStackTrace();
   } catch (Exception e) {
     JOptionPane.showMessageDialog(
         null, "Exception Erro: " + e.getMessage(), "ClasseDAO Func. Excluir", 0);
     e.printStackTrace();
   } finally {
     ps.close();
     con.close();
   }
 }
  @Override
  public HTTPResponse update(HTTPRequest request, HTTPResponse response) {
    Key key = Key.create(request, response);
    Connection connection = getConnection();

    PreparedStatement statement = null;
    try {
      JdbcUtil.startTransaction(connection);
      statement =
          connection.prepareStatement(
              "update response set headers = ?, cachetime = ? where uri = ? and vary = ?");
      statement.setString(1, response.getHeaders().toJSON());
      statement.setTimestamp(2, new Timestamp(DateTimeUtils.currentTimeMillis()));
      statement.setString(3, key.getURI().toString());
      statement.setString(4, key.getVary().toJSON());
      statement.executeUpdate();
      connection.commit();
      return getImpl(connection, key);
    } catch (SQLException e) {
      JdbcUtil.rollback(connection);
      JdbcUtil.close(connection);
      throw new DataAccessException(e);
    } finally {
      JdbcUtil.endTransaction(connection);
      JdbcUtil.close(statement);
    }
  }
 public String insertarEmpleado(Empleado empleado) {
   String mensaje = null;
   try {
     cn = Conexion.realizarConexion();
     String sql = "insert into empleado values(?,?,?,?,?,?,?,?)";
     ps = cn.prepareStatement(sql);
     ps.setString(1, empleado.getCodigo());
     ps.setString(2, empleado.getPaterno());
     ps.setString(3, empleado.getMaterno());
     ps.setString(4, empleado.getNombre());
     ps.setString(5, empleado.getCiudad());
     ps.setString(6, empleado.getDireccion());
     ps.setString(7, empleado.getUsuario());
     ps.setString(8, empleado.getClave());
     ps.executeUpdate();
   } catch (ClassNotFoundException ex) {
     mensaje = ex.getMessage();
   } catch (SQLException ex) {
     mensaje = ex.getMessage();
   } finally {
     try {
       ps.close();
       cn.close();
     } catch (Exception ex) {
       mensaje = ex.getMessage();
     }
   }
   return mensaje;
 }
 @Override
 public int registraOrdine(Ordine ordine) throws PersistenceException { // ok
   Connection connection = this.datasource.getConnection();
   PreparedStatement statement = null;
   int i;
   if (this.getOrdineByCodice(ordine.getCodiceOrdine()) != null)
     throw new PersistenceException("Ordine gia presente");
   try {
     String str = "insert into ordini (id,codice,data,stato,cliente) values (?,?,?,?,?)";
     statement = connection.prepareStatement(str);
     IdBroker id = new IdBrokerPostgres();
     i = id.getId();
     statement.setInt(1, i);
     statement.setString(
         2, new ClienteDAOImpl().getClienteById(ordine.getCliente().getId()).getNome() + i);
     statement.setDate(3, new java.sql.Date(ordine.getData().getTime()));
     statement.setString(4, ordine.getStato());
     statement.setInt(5, ordine.getCliente().getId());
     statement.executeUpdate();
   } catch (SQLException e) {
     throw new PersistenceException(e.getMessage());
   } finally {
     try {
       if (statement != null) statement.close();
       if (connection != null) connection.close();
     } catch (SQLException e) {
       throw new PersistenceException(e.getMessage());
     }
   }
   return i;
 }
  public static int updateToBankFee(ConnectionProvider connectionProvider) throws ServletException {
    String strSql = "";
    strSql =
        strSql
            + "        UPDATE FIN_FINACC_TRANSACTION SET TRXTYPE='BF' WHERE FIN_PAYMENT_ID IS NULL AND C_GLITEM_ID IS NULL";

    int updateCount = 0;
    PreparedStatement st = null;

    try {
      st = connectionProvider.getPreparedStatement(strSql);

      updateCount = st.executeUpdate();
    } catch (SQLException e) {
      log4j.error("SQL error in query: " + strSql + "Exception:" + e);
      throw new ServletException(
          "@CODE=" + Integer.toString(e.getErrorCode()) + "@" + e.getMessage());
    } catch (Exception ex) {
      log4j.error("Exception in query: " + strSql + "Exception:" + ex);
      throw new ServletException("@CODE=@" + ex.getMessage());
    } finally {
      try {
        connectionProvider.releasePreparedStatement(st);
      } catch (Exception ignore) {
        ignore.printStackTrace();
      }
    }
    return (updateCount);
  }
  public static int createPreference(ConnectionProvider connectionProvider)
      throws ServletException {
    String strSql = "";
    strSql =
        strSql
            + "           INSERT INTO ad_preference ("
            + "           ad_preference_id, ad_client_id, ad_org_id, isactive,"
            + "           createdby, created, updatedby, updated,attribute"
            + "           ) VALUES ("
            + "           get_uuid(), '0', '0', 'Y', '0', NOW(), '0', NOW(),'UpdatedTransactionTypeV2')";

    int updateCount = 0;
    PreparedStatement st = null;

    try {
      st = connectionProvider.getPreparedStatement(strSql);

      updateCount = st.executeUpdate();
    } catch (SQLException e) {
      log4j.error("SQL error in query: " + strSql + "Exception:" + e);
      throw new ServletException(
          "@CODE=" + Integer.toString(e.getErrorCode()) + "@" + e.getMessage());
    } catch (Exception ex) {
      log4j.error("Exception in query: " + strSql + "Exception:" + ex);
      throw new ServletException("@CODE=@" + ex.getMessage());
    } finally {
      try {
        connectionProvider.releasePreparedStatement(st);
      } catch (Exception ignore) {
        ignore.printStackTrace();
      }
    }
    return (updateCount);
  }
Exemple #15
0
  public void UpdateCustomer(CustomerDTO customer)
      throws ClassNotFoundException, SQLException, Exception {
    String sql = "";
    Connection conn = null;
    PreparedStatement stm = null;

    try {
      conn = getConnection();
      String stuempid = customer.getStuemp_no();
      sql =
          "update ykt_cur.t_cif_customer set password='******' where stuemp_no='"
              + stuempid
              + "'";
      stm = conn.prepareStatement(sql);
      stm.executeUpdate();
    } catch (SQLException e) {
      logger.error("²éѯÊý¾Ý¿âʧ°Ü");
      throw (e);
    } catch (Exception e) {
      e.printStackTrace();
      throw (e);
    } finally {
      if (stm != null) {
        stm.close();
      }
    }
  }
 public int updateBook(Book bo) {
   int x = 0;
   try {
     con = JdbcUtil.getMysqlConnection();
     System.out.println("update 2");
     ps =
         con.prepareStatement(
             "update jlcbooks set bname=?,author=?,pub=?,cost=?,edition=?,isbn=? where bid=?");
     System.out.println("update 3");
     System.out.println(bo.getBid());
     ps.setString(7, bo.getBid());
     ps.setString(1, bo.getBname());
     ps.setString(2, bo.getAuthor());
     ps.setString(3, bo.getPub());
     ps.setString(4, bo.getCost());
     ps.setString(5, bo.getEdi());
     ps.setString(6, bo.getIsbn());
     x = ps.executeUpdate();
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     JdbcUtil.cleanup(ps, con);
   }
   return x;
 }
Exemple #17
0
  void update_war(int db_id, long duration, long remaining, long time_to_start, int current_chain) {
    Connection con = null;
    try {
      con = pool.getConnection(timeout);

      PreparedStatement s =
          con.prepareStatement(
              "UPDATE `wars` SET `duration` = ? ,`remaining` = ?, `time_to_start` = ?, `current_chain` = ? WHERE id = ?");
      s.setLong(1, duration);
      s.setLong(2, remaining);
      s.setLong(3, time_to_start);
      s.setInt(4, current_chain);
      s.setInt(5, db_id);
      s.executeUpdate();
      s.close();
    } catch (SQLException ex) {
      Logger.getLogger(DBAccess.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
      try {
        if (con != null) {
          con.close();
        }
      } catch (SQLException ex) {
        Logger.getLogger(DBAccess.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
  }
Exemple #18
0
  void joinChannel(Channel channel) {
    Connection con = null;
    try {
      con = pool.getConnection(timeout);

      PreparedStatement s = con.prepareStatement("INSERT INTO `channels` (`channel`) VALUES (?)");
      s.setString(1, channel.getName().toLowerCase());
      s.executeUpdate();
      s.close();

      if (!this.channel_data.containsKey(channel.getName().toLowerCase())) {
        ChannelInfo new_channel = new ChannelInfo(channel.getName().toLowerCase());
        new_channel.setDefaultOptions();

        this.channel_data.put(channel.getName().toLowerCase(), new_channel);
      }

      this.saveChannelSettings(this.channel_data.get(channel.getName().toLowerCase()));
    } catch (SQLException ex) {
      Logger.getLogger(DBAccess.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
      try {
        if (con != null) {
          con.close();
        }
      } catch (SQLException ex) {
        Logger.getLogger(DBAccess.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
  }
Exemple #19
0
  public void removeFromChannelGroup(String group, ChannelInfo channel) {
    Connection con = null;
    try {
      con = pool.getConnection(timeout);

      PreparedStatement s =
          con.prepareStatement(
              "DELETE `channel_groups`.* FROM `channel_groups` INNER JOIN `channels` ON (`channel_groups`.`channel_id` = `channels`.`id`) WHERE `channels`.`channel` = ? AND `channel_groups`.`name` = ?");
      s.setString(1, channel.channel);
      s.setString(2, group);
      s.executeUpdate();
      s.close();

      // Will do nothing if the channel is not in the list.
      this.channel_groups.get(group.toLowerCase()).remove(channel);
    } catch (SQLException ex) {
      Logger.getLogger(DBAccess.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
      try {
        if (con != null) {
          con.close();
        }
      } catch (SQLException ex) {
        Logger.getLogger(DBAccess.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
  }
Exemple #20
0
  public void addToChannelGroup(String group, ChannelInfo channel) {
    Connection con = null;
    try {
      con = pool.getConnection(timeout);

      PreparedStatement s =
          con.prepareStatement(
              "REPLACE INTO `channel_groups` SET `name` = ?, `channel_id` = (SELECT `id` FROM `channels` WHERE `channel` = ?)");
      s.setString(1, group.toLowerCase());
      s.setString(2, channel.channel.toLowerCase());
      s.executeUpdate();
      s.close();

      // Will do nothing if the channel is not in the list.
      if (!this.channel_groups.containsKey(group.toLowerCase())) {
        this.channel_groups.put(group.toLowerCase(), new HashSet<>());
      }

      this.channel_groups.get(group.toLowerCase()).add(channel);
    } catch (SQLException ex) {
      Logger.getLogger(DBAccess.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
      try {
        if (con != null) {
          con.close();
        }
      } catch (SQLException ex) {
        Logger.getLogger(DBAccess.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
  }
Exemple #21
0
 public int update(String tableName, String colName, Object newValue, Object oldValue)
     throws SQLException {
   // syntax:
   // update [table] set [column] = [new value]
   // where [column] = [old value]
   int updated = 0;
   boolean hasWhere = false;
   if ((oldValue != null) && !(oldValue.equals(""))) {
     hasWhere = true;
   }
   PreparedStatement pstmt = pstmtBuilder.buildUpdateStatement(conn, tableName, colName, hasWhere);
   try {
     pstmt.setObject(1, newValue);
     if (hasWhere) {
       pstmt.setObject(2, oldValue);
     }
     updated = pstmt.executeUpdate();
   } catch (SQLException sqle) {
     System.out.println(sqle);
   } catch (Exception e) {
     System.out.println(e);
   } finally {
     try {
       pstmt.close();
       conn.close();
     } catch (Exception e) {
       System.out.println(e);
     }
   }
   return updated;
 }
 public void deleteFromDB(PreparedStatement ps) throws SQLException {
   if (dbid == -1) {
     throw new IllegalArgumentException("Can't delete non-DB OrthologyPair from DB!");
   }
   ps.setInt(1, dbid);
   ps.executeUpdate();
   dbid = -1;
 }
Exemple #23
0
 public void excluir(int idobj, Transacao tr) throws Exception {
   Connection con = tr.obterConexao();
   String sql = "delete from usuario where id=?";
   PreparedStatement ps = con.prepareStatement(sql);
   ps.setInt(1, idobj);
   int result = ps.executeUpdate();
   System.out.println("apagado com sucesso");
 } // excluir
  /**
   * Elimina al registro a través de la entidad dada por vData.
   *
   * <p><b> delete from GRLRegistroPNC where iEjercicio = ? AND iConsecutivoPNC = ? </b>
   *
   * <p><b> Campos Llave: iEjercicio,iConsecutivoPNC, </b>
   *
   * @param vData TVDinRep - VO Dinámico que contiene a la entidad a Insertar.
   * @param cnNested Connection - Conexión anidada que permite que el método se encuentre dentro de
   *     una transacción mayor.
   * @throws DAOException - Excepción de tipo DAO
   * @return boolean - En caso de ser o no eliminado el registro.
   */
  public boolean delete(TVDinRep vData, Connection cnNested) throws DAOException {
    DbConnection dbConn = null;
    Connection conn = cnNested;
    PreparedStatement lPStmt = null;
    boolean lSuccess = true;
    String cMsg = "";
    try {
      if (cnNested == null) {
        dbConn = new DbConnection(dataSourceName);
        conn = dbConn.getConnection();
        conn.setAutoCommit(false);
        conn.setTransactionIsolation(2);
      }

      // Ajustar Where de acuerdo a requerimientos...
      String lSQL = "delete from GRLRegistroPNC where iEjercicio = ? AND iConsecutivoPNC = ?  ";
      // ...

      lPStmt = conn.prepareStatement(lSQL);

      lPStmt.setInt(1, vData.getInt("iEjercicio"));
      lPStmt.setInt(2, vData.getInt("iConsecutivoPNC"));

      lPStmt.executeUpdate();
      if (cnNested == null) {
        conn.commit();
      }
    } catch (SQLException sqle) {
      lSuccess = false;
      cMsg = "" + sqle.getErrorCode();
    } catch (Exception ex) {
      warn("delete", ex);
      if (cnNested == null) {
        try {
          conn.rollback();
        } catch (Exception e) {
          fatal("delete.rollback", e);
        }
      }
      lSuccess = false;
    } finally {
      try {
        if (lPStmt != null) {
          lPStmt.close();
        }
        if (cnNested == null) {
          if (conn != null) {
            conn.close();
          }
          dbConn.closeConnection();
        }
      } catch (Exception ex2) {
        warn("delete.close", ex2);
      }
      if (lSuccess == false) throw new DAOException(cMsg);
      return lSuccess;
    }
  }
  public boolean delete(Local_dept local_dept) throws SQLException {

    PreparedStatement stmt = conexao.prepareStatement("delete from local_dept where num_dept = ? ");
    stmt.setInt(1, local_dept.getNum_dept());
    int linhas = stmt.executeUpdate();

    stmt.close();
    return linhas > 0;
  }
Exemple #26
0
 // 删除的方法
 public void deleteLink(int id) {
   try {
     ps = connection.prepareStatement("delete from TG_link where id_link=?");
     ps.setInt(1, id);
     ps.executeUpdate();
     ps.close();
   } catch (SQLException ex) {
   }
 }
Exemple #27
0
  int create_war(
      Channel channel,
      String starter,
      String name,
      long base_duration,
      long duration,
      long remaining,
      long time_to_start,
      int total_chains,
      int current_chain,
      int break_duration,
      boolean do_randomness) {
    int id = 0;
    Connection con = null;
    try {
      con = pool.getConnection(timeout);

      PreparedStatement s =
          con.prepareStatement(
              "INSERT INTO `wars` (`channel`, `starter`, `name`, `base_duration`, `randomness`, `delay`, `duration`, `remaining`, `time_to_start`, `total_chains`, `current_chain`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
              Statement.RETURN_GENERATED_KEYS);
      s.setString(1, channel.getName().toLowerCase());
      s.setString(2, starter);
      s.setString(3, name);
      s.setLong(4, base_duration);
      s.setBoolean(5, do_randomness);
      s.setLong(6, break_duration);
      s.setLong(7, duration);
      s.setLong(8, remaining);
      s.setLong(9, time_to_start);
      s.setInt(10, total_chains);
      s.setInt(11, current_chain);
      s.executeUpdate();

      ResultSet rs = s.getGeneratedKeys();

      if (rs.next()) {
        id = rs.getInt(1);
      }

      rs.close();
      s.close();
    } catch (SQLException ex) {
      Logger.getLogger(DBAccess.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
      try {
        if (con != null) {
          con.close();
        }
      } catch (SQLException ex) {
        Logger.getLogger(DBAccess.class.getName()).log(Level.SEVERE, null, ex);
      }
    }

    return id;
  }
Exemple #28
0
  /** ************************** */
  public void InsertPrepared() {
    try {
      // use prepared statement to insert data

      System.out.println("\n ** Using prepared statement, faster than regular statement  ** ");
      SecondStatement.setString(1, "Name 1");
      SecondStatement.setString(2, "00000000");
      SecondStatement.setString(3, "250000");
      SecondStatement.executeUpdate();
      System.out.println("Prepared: new tuple inserted ");
      SecondStatement.setString(1, "Name 2");
      SecondStatement.setString(2, "111111");
      SecondStatement.setString(3, "887700");
      SecondStatement.executeUpdate();
      System.out.println("Prepared: new tuple inserted \n\n ");
    } catch (Exception e) {
      System.out.println(" Error 1: " + e.toString());
    }
  }
Exemple #29
0
 // 添加的方法
 public void insertLink(LinkForm form) {
   try {
     ps = connection.prepareStatement("insert into TG_link values (?,?)");
     ps.setString(1, form.getLinkName());
     ps.setString(2, form.getLinkAddress());
     ps.executeUpdate();
     ps.close();
   } catch (SQLException ex) {
   }
 }
  public static void delInterestCourse(Connection con, String cstm_id) throws Exception {
    PreparedStatement pstmt = null;
    String sql = "";
    int index = 1;

    sql = " delete from t_fl_interest_courses where cstm_id = ? ";
    pstmt = con.prepareStatement(sql);
    pstmt.setString(index++, cstm_id);
    pstmt.executeUpdate();
    pstmt.close();
  }