コード例 #1
0
  public void update(Animal a) {
    if (a == null || a.getId() == 0) {
      throw new IllegalArgumentException(
          "Attempt to update a non-existing or non persisted animal");
    }

    Connection connection = null;
    PreparedStatement statement = null;

    try {
      connection = getConnection();
      statement =
          connection.prepareStatement(
              "UPDATE animals set name = ?, species = ?, energy = ?, aliveyn = ? where id = ?");
      statement.setString(1, a.getName());
      statement.setString(2, a.getSpecies());
      statement.setInt(3, a.getEnergy());
      statement.setBoolean(4, a.isAlive());
      statement.setLong(5, a.getId());

      statement.executeUpdate();
      connection.commit();
    } catch (SQLException e) {
      try {
        connection.rollback();
      } catch (SQLException e1) {
        e1.printStackTrace();
      }
      e.printStackTrace();

      throw new RuntimeException("Data error: " + e.getMessage());
    } finally {

      if (statement != null) {
        try {
          statement.close();
        } catch (SQLException e) {
          throw new RuntimeException("Unable to close statement");
        }
      }
      if (connection != null) {
        try {
          connection.close();
        } catch (SQLException e) {
          throw new RuntimeException("Unable to close connection");
        }
      }
    }
  }
コード例 #2
0
  public void create(Animal a) {
    Connection connection = null;
    PreparedStatement statement = null;
    try {
      connection = getConnection();
      statement =
          connection.prepareStatement(
              "INSERT INTO ANIMALS(id,name, species, energy, aliveyn) VALUES(animals_seq.nextval, ?, ?, ? ,?)");
      statement.setString(1, a.getName());
      statement.setString(2, a.getSpecies());
      statement.setInt(3, a.getEnergy());
      statement.setBoolean(4, a.isAlive());

      statement.executeUpdate();
      connection.commit();
    } catch (SQLException e) {
      try {
        connection.rollback();
      } catch (SQLException e1) {
        e1.printStackTrace();
      }
      e.printStackTrace();
    } finally {

      if (statement != null) {
        try {
          statement.close();
        } catch (SQLException e) {
          throw new RuntimeException("Unable to close statement");
        }
      }
      if (connection != null) {
        try {
          connection.close();
        } catch (SQLException e) {
          throw new RuntimeException("Unable to close connection");
        }
      }
    }
  }