コード例 #1
1
  /**
   * Returns orders with given identifiers.
   *
   * @param ids Orders identifiers.
   * @return List of order entities.
   */
  public List<Order> findOrders(String[] ids) throws DBException {
    List<Order> ordersList = new ArrayList<Order>();
    Statement stmt = null;
    ResultSet rs = null;
    Connection con = null;
    try {
      con = getConnection();

      // create SQL query like "... id IN (1, 2, 7)"
      StringBuilder query = new StringBuilder("SELECT * FROM orders WHERE id IN (");
      for (String idAsString : ids) {
        query.append(idAsString).append(',');
      }
      query.deleteCharAt(query.length() - 1);
      query.append(')');

      stmt = con.createStatement();
      rs = stmt.executeQuery(query.toString());
      while (rs.next()) {
        ordersList.add(extractOrder(rs));
      }
      con.commit();
    } catch (SQLException ex) {
      rollback(con);
      throw new DBException(Messages.ERR_CANNOT_OBTAIN_ORDERS_BY_IDENTIFIERS, ex);
    } finally {
      close(con, stmt, rs);
    }
    return ordersList;
  }
コード例 #2
1
  public boolean updateStatus(List<Long> lumberLogIds) {
    Logger logger = Logger.getLogger("dao");
    StringBuilder updateSql = new StringBuilder(" update lumberlog set Status = 0 ");
    updateSql.append(" where id in(");
    for (Long id : lumberLogIds) {
      updateSql.append(id).append(",");
    }
    updateSql.deleteCharAt(updateSql.length() - 1);
    updateSql.append(")");

    boolean status = true;

    Connection con = null;
    Statement stm = null;
    try {
      con = DataAccess.getInstance().getDatabaseConnection();
      con.setAutoCommit(true);
      stm = con.createStatement();
      logger.info(updateSql.toString());
      int count = stm.executeUpdate(updateSql.toString());

    } catch (Exception e) {
      status = false;
      logger.warning(e.getMessage());
      logger.log(Level.INFO, "Error", e);
    } finally {
      if (stm != null)
        try {
          stm.close();
        } catch (Exception e) {
        }
    }

    return status;
  }
コード例 #3
1
  public void bindParams(PreparedStatement ps, EqlRun eqlRun, Logger logger) {
    this.eqlRun = eqlRun;
    boundParams = new StringBuilder();
    this.ps = ps;

    switch (eqlRun.getPlaceHolderType()) {
      case AUTO_SEQ:
        for (int i = 0; i < eqlRun.getPlaceholderNum(); ++i)
          setParam(i, getParamByIndex(i), ParamExtra.Normal);
        break;
      case MANU_SEQ:
        for (int i = 0; i < eqlRun.getPlaceholderNum(); ++i)
          setParam(i, findParamBySeq(i + 1), ParamExtra.Normal);
        break;
      case VAR_NAME:
        for (int i = 0; i < eqlRun.getPlaceholderNum(); ++i)
          setParam(i, findParamByName(i), ParamExtra.Normal);
        break;
      default:
        break;
    }

    bindExtraParams();

    if (boundParams.length() > 0) logger.debug("param: {}", boundParams);
  }
コード例 #4
1
  // Hàm hỗ trợ Update CSDL
  // UPDATE TableName SET ColumnName = ColumnValue WHERE Condiotion;
  public boolean Update(String TableName, HashMap<String, Object> ColumnValues, String Condition)
      throws Exception {
    // Khai báo biến StringBuilder để tạo chuỗi Select.
    StringBuilder query = new StringBuilder("UPDATE " + TableName + " SET ");

    // Duyệt và đưa thông tin tên cột và giá trị của cột vào câu query
    for (String key : ColumnValues.keySet()) {
      query.append(key).append(" = '").append(ColumnValues.get(key).toString()).append("',");
    }
    // Cắt bớt ký tự ',' cuối câu
    query = query.delete(query.length() - 1, query.length());
    // Đưa câu lệnh điều kiện vào trong câu query
    this.AddCondition(query, Condition);
    // Chèn ký tự ';' vào cuối dòng lệnh của để cách các câu lệnh.
    query.append(";");
    // Thực thi câu query và trả kết quả ra ngoài
    return this._connect.executeUpdate(query.toString()) > 0;
  }
コード例 #5
1
 public String tableColumns(String tableName, String columnPrefix) throws SQLException {
   ResultSet columns = executeQuery(driver.getQueries().getColumns(tableName));
   StringBuilder columnsBuilder = new StringBuilder();
   while (columns.next()) {
     if (columnsBuilder.length() > 0) columnsBuilder.append(',');
     columnsBuilder.append(columnPrefix).append(columns.getString("property.name"));
   }
   return columnsBuilder.toString();
 }
コード例 #6
1
  public String makeWholeUnionCall(String question) {
    List<String> letters = new ArrayList<String>();
    letters.add("a");
    letters.add("b");
    letters.add("c");
    letters.add("d");
    letters.add("e");
    letters.add("f");

    StringBuilder wholeSelect = new StringBuilder();
    wholeSelect.append("COPY (");
    for (String letter : letters) {
      wholeSelect.append(makeSelectForUnion(question, letter));
      wholeSelect.append(" UNION ");
    }
    wholeSelect.delete(wholeSelect.length() - 6, wholeSelect.length());
    wholeSelect.append(") TO '/tmp/p_").append(question).append(".csv' WITH CSV;");
    return wholeSelect.toString();
  }
コード例 #7
1
 /*
  * create method, that read from a txt file and read the MySQL language and write to the database.
  */
 public void createDB() {
   try {
     BufferedReader br = new BufferedReader(new FileReader("db_schema.txt"));
     String line = null;
     StringBuilder sb = new StringBuilder();
     while ((line = br.readLine()) != null) {
       sb.append(line);
       if (sb.length() > 0
           && sb.charAt(sb.length() - 1) == ';') { // see if it is the end of one line of command
         statement.executeUpdate(sb.toString());
         sb = new StringBuilder();
       }
     }
     br.close();
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } catch (SQLException e) {
     e.printStackTrace();
   }
 }
コード例 #8
1
  // Hàm hỗ trợ Insert xuống CSDL.
  // INSERT INTO TableName (columnName...) VALUES (column Values...);
  public boolean Insert(String TableName, HashMap<String, Object> ColumnValues) throws Exception {
    // Khai báo biến StringBuilder để tạo chuỗi Select.
    StringBuilder query = new StringBuilder("INSERT INTO " + TableName);
    // Khai báo biến StringBuilder để tạo chuỗi Column Values.
    StringBuilder valueInsert = new StringBuilder();

    query.append("(");
    // Duyệt và đưa thông tin tên cột và giá trị của cột vào câu query
    for (String key : ColumnValues.keySet()) {
      query.append(key).append(",");
      valueInsert.append("'").append(ColumnValues.get(key).toString()).append("' ,");
    }
    // Cắt bớt ký tự ',' cuối câu
    query = query.delete(query.length() - 1, query.length());
    valueInsert = valueInsert.delete(valueInsert.length() - 1, valueInsert.length());

    // Đưa giá trị của cột vào câu query
    query.append(") VALUES(").append(valueInsert.toString()).append(")");
    // Chèn ký tự ';' vào cuối dòng lệnh của để cách các câu lệnh.
    query.append(";");
    // Thực thi câu query và trả kết quả ra ngoài
    return this._connect.executeUpdate(query.toString()) > 0;
  }
コード例 #9
1
  /**
   * Returns menu items with given identifiers.
   *
   * @param ids Identifiers of menu items.
   * @return List of menu item entities.
   */
  public List<CatalogItem> findCatalogItems(String[] ids) throws DBException {
    List<CatalogItem> catalogItemList = new ArrayList<>();
    Statement stmt = null;
    ResultSet rs = null;
    Connection con = null;
    try {
      con = getConnection();

      // create SQL query like "... id IN (1, 2, 7)"
      StringBuilder query =
          new StringBuilder(
              "SELECT \n"
                  + "catalog.hot as 'hot',\n"
                  + "catalog.id,\n"
                  + "catalog.name as 'Hotel',\n"
                  + "categories.name as 'Category',\n"
                  + "type_hotel.name as 'Hotel type',\n"
                  + "catalog.q_people,\n"
                  + "catalog.price\n"
                  + "FROM catalog\n"
                  + "LEFT JOIN categories ON categories.id = catalog.category_id \n"
                  + "LEFT JOIN type_hotel on catalog.type_hotel_id = type_hotel.id \n"
                  + "\n"
                  + "WHERE catalog.id IN (");
      for (String idAsString : ids) {
        query.append(idAsString).append(',');
      }
      query.deleteCharAt(query.length() - 1);
      query.append(')');

      stmt = con.createStatement();
      rs = stmt.executeQuery(query.toString());
      while (rs.next()) {
        catalogItemList.add(extractCatalogItem(rs));
      }
    } catch (SQLException ex) {
      rollback(con);
      LOG.error(ex);
      //            ex.printStackTrace();
      //            throw new DBException(
      //                    Messages.ERR_CANNOT_OBTAIN_MENU_ITEMS_BY_IDENTIFIERS, ex);
    } finally {
      close(con, stmt, rs);
    }
    return catalogItemList;
  }
コード例 #10
1
ファイル: Finder.java プロジェクト: taylorkelly/BigBrother
  private static final void mysqlFind(
      final Plugin plugin,
      final String playerName,
      final Location location,
      final int radius,
      final WorldManager manager,
      final ArrayList<Player> players) {

    BBPlayerInfo hunted = BBUsersTable.getInstance().getUserByName(playerName);

    PreparedStatement ps = null;
    ResultSet rs = null;

    HashMap<Integer, Integer> creations = new HashMap<Integer, Integer>();
    HashMap<Integer, Integer> destructions = new HashMap<Integer, Integer>();
    HashMap<Integer, Integer> explosions = new HashMap<Integer, Integer>();
    HashMap<Integer, Integer> burns = new HashMap<Integer, Integer>();

    Connection conn = null;

    try {
      conn = ConnectionManager.getConnection();
      if (conn == null) return;
      // TODO maybe more customizable actions?
      String actionString =
          "action IN('"
              + Action.BLOCK_BROKEN.ordinal()
              + "', '"
              + Action.BLOCK_PLACED.ordinal()
              + "', '"
              + Action.LEAF_DECAY.ordinal()
              + "', '"
              + Action.TNT_EXPLOSION.ordinal()
              + "', '"
              + Action.CREEPER_EXPLOSION.ordinal()
              + "', '"
              + Action.MISC_EXPLOSION.ordinal()
              + "', '"
              + Action.LAVA_FLOW.ordinal()
              + "', '"
              + Action.BLOCK_BURN.ordinal()
              + "')";
      ps =
          conn.prepareStatement(
              "SELECT action, type FROM "
                  + BBDataTable.getInstance().getTableName()
                  + " WHERE "
                  + actionString
                  + " AND rbacked = 0 AND x < ? AND x > ? AND y < ? AND y > ?  AND z < ? AND z > ? AND player = ? AND world = ? order by date desc");

      ps.setInt(1, location.getBlockX() + radius);
      ps.setInt(2, location.getBlockX() - radius);
      ps.setInt(3, location.getBlockY() + radius);
      ps.setInt(4, location.getBlockY() - radius);
      ps.setInt(5, location.getBlockZ() + radius);
      ps.setInt(6, location.getBlockZ() - radius);
      ps.setInt(7, hunted.getID());
      ps.setInt(8, manager.getWorld(location.getWorld().getName()));
      rs = ps.executeQuery();
      conn.commit();

      int size = 0;
      while (rs.next()) {
        Action action = Action.values()[rs.getInt("action")];
        int type = rs.getInt("type");

        switch (action) {
          case BLOCK_BROKEN:
          case LEAF_DECAY:
            if (destructions.containsKey(type)) {
              destructions.put(type, destructions.get(type) + 1);
              size++;
            } else {
              destructions.put(type, 1);
              size++;
            }
            break;
          case BLOCK_PLACED:
            if (creations.containsKey(type)) {
              creations.put(type, creations.get(type) + 1);
              size++;
            } else {
              creations.put(type, 1);
              size++;
            }
            break;
          case TNT_EXPLOSION:
          case CREEPER_EXPLOSION:
          case MISC_EXPLOSION:
            if (explosions.containsKey(type)) {
              explosions.put(type, explosions.get(type) + 1);
              size++;
            } else {
              explosions.put(type, 1);
              size++;
            }
          case BLOCK_BURN:
            if (burns.containsKey(type)) {
              burns.put(type, burns.get(type) + 1);
              size++;
            } else {
              burns.put(type, 1);
              size++;
            }
            break;
          case LAVA_FLOW:
            if (creations.containsKey(type)) {
              creations.put(type, creations.get(type) + 1);
              size++;
            } else {
              creations.put(type, 1);
              size++;
            }
            break;
        }
      }
      if (size > 0) {
        StringBuilder creationList = new StringBuilder();
        creationList.append(ChatColor.AQUA.toString());
        creationList.append("Placed Blocks: ");
        creationList.append(ChatColor.WHITE.toString());
        for (Entry<Integer, Integer> entry : creations.entrySet()) {
          creationList.append(Material.getMaterial(entry.getKey()));
          creationList.append(" (");
          creationList.append(entry.getValue());
          creationList.append("), ");
        }
        if (creationList.toString().contains(",")) {
          creationList.delete(creationList.lastIndexOf(","), creationList.length());
        }
        StringBuilder brokenList = new StringBuilder();
        brokenList.append(ChatColor.RED.toString());
        brokenList.append("Broken Blocks: ");
        brokenList.append(ChatColor.WHITE.toString());
        for (Entry<Integer, Integer> entry : destructions.entrySet()) {
          brokenList.append(Material.getMaterial(entry.getKey()));
          brokenList.append(" (");
          brokenList.append(entry.getValue());
          brokenList.append("), ");
        }
        if (brokenList.toString().contains(",")) {
          brokenList.delete(brokenList.lastIndexOf(","), brokenList.length());
        }
        StringBuilder explodeList = new StringBuilder();
        explodeList.append(ChatColor.RED.toString());
        explodeList.append("Exploded Blocks: ");
        explodeList.append(ChatColor.WHITE.toString());
        for (Entry<Integer, Integer> entry : explosions.entrySet()) {
          explodeList.append(Material.getMaterial(entry.getKey()));
          explodeList.append(" (");
          explodeList.append(entry.getValue());
          explodeList.append("), ");
        }
        if (explodeList.toString().contains(",")) {
          explodeList.delete(explodeList.lastIndexOf(","), explodeList.length());
        }

        StringBuilder burnList = new StringBuilder();
        burnList.append(ChatColor.RED.toString());
        burnList.append("Burned Blocks: ");
        burnList.append(ChatColor.WHITE.toString());
        for (Entry<Integer, Integer> entry : burns.entrySet()) {
          burnList.append(Material.getMaterial(entry.getKey()));
          burnList.append(" (");
          burnList.append(entry.getValue());
          burnList.append("), ");
        }
        if (burnList.toString().contains(",")) {
          burnList.delete(burnList.lastIndexOf(","), burnList.length());
        }
        for (Player player : players) {
          player.sendMessage(
              BigBrother.premessage + playerName + " has made " + size + " modifications");
          if (creations.entrySet().size() > 0) {
            player.sendMessage(creationList.toString());
          }
          if (destructions.entrySet().size() > 0) {
            player.sendMessage(brokenList.toString());
          }
          if (explosions.entrySet().size() > 0) {
            player.sendMessage(explodeList.toString());
          }
          if (burns.entrySet().size() > 0) {
            player.sendMessage(burnList.toString());
          }
        }
      } else {
        for (Player player : players) {
          player.sendMessage(
              BigBrother.premessage + playerName + " has no modifications in this area.");
        }
      }
    } catch (SQLException ex) {
      BBLogging.severe("Find SQL Exception", ex);
    } finally {
      ConnectionManager.cleanup("Find SQL", conn, ps, rs);
    }
  }
コード例 #11
1
ファイル: Finder.java プロジェクト: taylorkelly/BigBrother
  private static final void mysqlFind(
      final Plugin plugin,
      final Location location,
      final int radius,
      final WorldManager manager,
      final ArrayList<Player> players) {
    PreparedStatement ps = null;
    ResultSet rs = null;
    Connection conn = null;
    HashMap<BBPlayerInfo, Integer> modifications = new HashMap<BBPlayerInfo, Integer>();
    try {
      conn = ConnectionManager.getConnection();
      if (conn == null) return;
      // TODO maybe more customizable actions?
      String actionString =
          "action IN('"
              + Action.BLOCK_BROKEN.ordinal()
              + "', '"
              + Action.BLOCK_PLACED.ordinal()
              + "', '"
              + Action.LEAF_DECAY.ordinal()
              + "', '"
              + Action.TNT_EXPLOSION.ordinal()
              + "', '"
              + Action.CREEPER_EXPLOSION.ordinal()
              + "', '"
              + Action.MISC_EXPLOSION.ordinal()
              + "', '"
              + Action.LAVA_FLOW.ordinal()
              + "', '"
              + Action.BLOCK_BURN.ordinal()
              + "')";

      /*
       * org.h2.jdbc.JdbcSQLException: Column "ID" must be in the GROUP BY
       * list; SQL statement:
       */
      if (BBSettings.usingDBMS(DBMS.H2) || BBSettings.usingDBMS(DBMS.POSTGRES)) {
        ps =
            conn.prepareStatement(
                "SELECT player, count(player) AS modifications FROM "
                    + BBDataTable.getInstance().getTableName()
                    + " WHERE "
                    + actionString
                    + " AND rbacked = '0' AND x < ? AND x > ? AND y < ? AND y > ? AND z < ? AND z > ? AND world = ? GROUP BY id,player ORDER BY id DESC");
      } else {
        ps =
            conn.prepareStatement(
                "SELECT player, count(player) AS modifications FROM "
                    + BBDataTable.getInstance().getTableName()
                    + " WHERE "
                    + actionString
                    + " AND rbacked = '0' AND x < ? AND x > ? AND y < ? AND y > ? AND z < ? AND z > ? AND world = ? GROUP BY player ORDER BY id DESC");
      }
      ps.setInt(1, location.getBlockX() + radius);
      ps.setInt(2, location.getBlockX() - radius);
      ps.setInt(3, location.getBlockY() + radius);
      ps.setInt(4, location.getBlockY() - radius);
      ps.setInt(5, location.getBlockZ() + radius);
      ps.setInt(6, location.getBlockZ() - radius);
      ps.setInt(7, manager.getWorld(location.getWorld().getName()));
      rs = ps.executeQuery();
      conn.commit();

      int size = 0;
      while (rs.next()) {
        BBPlayerInfo player = BBUsersTable.getInstance().getUserByID(rs.getInt("player"));
        int mods = rs.getInt("modifications");
        modifications.put(player, mods);
        size++;
      }
      if (size > 0) {
        StringBuilder playerList = new StringBuilder();
        for (Entry<BBPlayerInfo, Integer> entry : modifications.entrySet()) {
          if (entry.getKey() != null) {
            playerList.append(entry.getKey().getName());
            playerList.append(" (");
            playerList.append(entry.getValue());
            playerList.append("), ");
          }
        }
        if (playerList.indexOf(",") != -1) {
          playerList.delete(playerList.lastIndexOf(","), playerList.length());
        }
        // TODO Put into sync'd runnable
        for (Player player : players) {
          player.sendMessage(
              BigBrother.premessage + playerList.length() + " player(s) have modified this area:");
          player.sendMessage(playerList.toString());
        }
      } else {
        for (Player player : players) {
          player.sendMessage(BigBrother.premessage + "No modifications in this area.");
        }
      }
    } catch (SQLException ex) {
      BBLogging.severe("Find SQL Exception", ex);
    } finally {
      ConnectionManager.cleanup("Find SQL", conn, ps, rs);
    }
  }
コード例 #12
1
ファイル: Finder.java プロジェクト: DanielChesters/BigBrother
  // TODO use IN(1,2,3)
  private void mysqlFind(boolean sqlite) {
    PreparedStatement ps = null;
    ResultSet rs = null;
    Connection conn = null;
    HashMap<String, Integer> modifications = new HashMap<String, Integer>();
    try {
      conn = ConnectionManager.getConnection();

      // TODO maybe more customizable actions?
      String actionString =
          "action IN('"
              + Action.BLOCK_BROKEN.ordinal()
              + "', '"
              + Action.BLOCK_PLACED.ordinal()
              + "', '"
              + Action.LEAF_DECAY.ordinal()
              + "', '"
              + Action.TNT_EXPLOSION.ordinal()
              + "', '"
              + Action.CREEPER_EXPLOSION.ordinal()
              + "', '"
              + Action.MISC_EXPLOSION.ordinal()
              + "', '"
              + Action.BLOCK_BURN.ordinal()
              + "')";
      ps =
          conn.prepareStatement(
              "SELECT player, count(player) AS modifications FROM "
                  + BBDataBlock.BBDATA_NAME
                  + " WHERE "
                  + actionString
                  + " AND rbacked = '0' AND x < ? AND x > ? AND y < ? AND y > ? AND z < ? AND z > ? AND world = ? GROUP BY player ORDER BY id DESC");

      ps.setInt(1, location.getBlockX() + radius);
      ps.setInt(2, location.getBlockX() - radius);
      ps.setInt(3, location.getBlockY() + radius);
      ps.setInt(4, location.getBlockY() - radius);
      ps.setInt(5, location.getBlockZ() + radius);
      ps.setInt(6, location.getBlockZ() - radius);
      ps.setInt(7, worlds.indexOf(location.getWorld()));
      rs = ps.executeQuery();
      conn.commit();

      int size = 0;
      while (rs.next()) {
        String player = rs.getString("player");
        int mods = rs.getInt("modifications");
        modifications.put(player, mods);
        size++;
      }
      if (size > 0) {
        StringBuilder playerList = new StringBuilder();
        for (Entry<String, Integer> entry : modifications.entrySet()) {
          playerList.append(entry.getKey());
          playerList.append(" (");
          playerList.append(entry.getValue());
          playerList.append("), ");
        }
        playerList.delete(playerList.lastIndexOf(","), playerList.length());
        for (Player player : players) {
          player.sendMessage(BigBrother.premessage + size + " player(s) have modified this area:");
          player.sendMessage(playerList.toString());
        }
      } else {
        for (Player player : players) {
          player.sendMessage(BigBrother.premessage + "No modifications in this area.");
        }
      }
    } catch (SQLException ex) {
      BigBrother.log.log(Level.SEVERE, "[BBROTHER]: Find SQL Exception", ex);
    } finally {
      try {
        if (rs != null) rs.close();
        if (ps != null) ps.close();
        if (conn != null) conn.close();
      } catch (SQLException ex) {
        BigBrother.log.log(Level.SEVERE, "[BBROTHER]: Find SQL Exception (on close)");
      }
    }
  }
コード例 #13
1
ファイル: LibRt.java プロジェクト: yamila87/rt_src
  public static int serDiccGroupByToWriter(
      ResultSet rs,
      Writer writer,
      int maxRows,
      String idPor,
      String[] idAcumulados,
      String campoAcumuladoNombre) {
    int rowsCount = 0;

    try {

      ArrayList<String> acumulado = null;
      String idActual = null;
      StringBuilder reg = null;
      reg = new StringBuilder();
      String value = "";

      if (rs != null) {
        ResultSetMetaData rsm = rs.getMetaData();
        int countCol = rsm.getColumnCount();
        String name = "";
        for (int i = 1; i <= countCol; i++) {
          name = rsm.getColumnName(i);
          reg.append(name.toLowerCase()).append("\t");
        }
        reg.append(campoAcumuladoNombre);

        writer.write(reg.toString() + EOL);

        while (rs.next()) {
          if (idActual == null) {
            reg = new StringBuilder();
            acumulado = new ArrayList<String>();
            idActual = rs.getString(idPor);

            for (int i = 1; i <= countCol; i++) {
              reg.append(rs.getString(i)).append("\t");
            }

            for (String id : idAcumulados) {
              value = rs.getString(id);
              if (!rs.wasNull()) {
                acumulado.add(rs.getString(id));
              }
            }

          } else {

            if (idActual.equals(rs.getString(idPor))) {
              for (String id : idAcumulados) {
                value = rs.getString(id);
                if (!rs.wasNull()) {
                  acumulado.add(rs.getString(id));
                }
              }
            } else {
              if (acumulado.size() > 0) {
                for (String str : acumulado) {
                  reg.append(str).append(",");
                }
                reg.deleteCharAt(reg.length() - 1);
              }
              reg.append(EOL);

              writer.write(reg.toString());
              rowsCount++;
              if (maxRows == rowsCount) {
                break;
              }

              idActual = rs.getString(idPor);
              reg = new StringBuilder();
              acumulado = new ArrayList<String>();

              for (int i = 1; i <= countCol; i++) {
                reg.append(rs.getString(i)).append("\t");
              }

              for (String id : idAcumulados) {
                value = rs.getString(id);
                if (!rs.wasNull()) {
                  acumulado.add(rs.getString(id));
                }
              }
            }
          }
        }

        if (acumulado.size() > 0) {
          for (String str : acumulado) {
            reg.append(str).append(",");
          }
          reg.deleteCharAt(reg.length() - 1);
        }
        reg.append(EOL);

        writer.write(reg.toString());
        rowsCount++;
      }
    } catch (SQLException e) {
      logm("ERR", 1, "Error al escribir registros", e);
    } catch (IOException e) {
      logm("ERR", 1, "Error al escribir registros", e);
    }
    return rowsCount;
  }
コード例 #14
0
ファイル: Finder.java プロジェクト: DanielChesters/BigBrother
  private void mysqlFind(boolean sqlite, String playerName) {
    PreparedStatement ps = null;
    ResultSet rs = null;

    HashMap<Integer, Integer> creations = new HashMap<Integer, Integer>();
    HashMap<Integer, Integer> destructions = new HashMap<Integer, Integer>();
    HashMap<Integer, Integer> explosions = new HashMap<Integer, Integer>();
    HashMap<Integer, Integer> burns = new HashMap<Integer, Integer>();

    Connection conn = null;

    try {
      conn = ConnectionManager.getConnection();

      // TODO maybe more customizable actions?
      String actionString =
          "action IN('"
              + Action.BLOCK_BROKEN.ordinal()
              + "', '"
              + Action.BLOCK_PLACED.ordinal()
              + "', '"
              + Action.LEAF_DECAY.ordinal()
              + "', '"
              + Action.TNT_EXPLOSION.ordinal()
              + "', '"
              + Action.CREEPER_EXPLOSION.ordinal()
              + "', '"
              + Action.MISC_EXPLOSION.ordinal()
              + "', '"
              + Action.BLOCK_BURN.ordinal()
              + "')";
      ps =
          conn.prepareStatement(
              "SELECT action, type FROM "
                  + BBDataBlock.BBDATA_NAME
                  + " WHERE "
                  + actionString
                  + " AND rbacked = 0 AND x < ? AND x > ? AND y < ? AND y > ?  AND z < ? AND z > ? AND player = ? AND world = ? order by date desc");

      ps.setInt(1, location.getBlockX() + radius);
      ps.setInt(2, location.getBlockX() - radius);
      ps.setInt(3, location.getBlockY() + radius);
      ps.setInt(4, location.getBlockY() - radius);
      ps.setInt(5, location.getBlockZ() + radius);
      ps.setInt(6, location.getBlockZ() - radius);
      ps.setString(7, playerName);
      ps.setInt(8, worlds.indexOf(location.getWorld()));
      rs = ps.executeQuery();
      conn.commit();

      int size = 0;
      while (rs.next()) {
        Action action = Action.values()[rs.getInt("action")];
        int type = rs.getInt("type");

        switch (action) {
          case BLOCK_BROKEN:
          case LEAF_DECAY:
            if (destructions.containsKey(type)) {
              destructions.put(type, destructions.get(type) + 1);
              size++;
            } else {
              destructions.put(type, 1);
              size++;
            }
            break;
          case BLOCK_PLACED:
            if (creations.containsKey(type)) {
              creations.put(type, creations.get(type) + 1);
              size++;
            } else {
              creations.put(type, 1);
              size++;
            }
            break;
          case TNT_EXPLOSION:
          case CREEPER_EXPLOSION:
          case MISC_EXPLOSION:
            if (explosions.containsKey(type)) {
              explosions.put(type, explosions.get(type) + 1);
              size++;
            } else {
              explosions.put(type, 1);
              size++;
            }
          case BLOCK_BURN:
            if (burns.containsKey(type)) {
              burns.put(type, burns.get(type) + 1);
              size++;
            } else {
              burns.put(type, 1);
              size++;
            }
            break;
        }
      }
      if (size > 0) {
        StringBuilder creationList = new StringBuilder();
        // creationList.append(Color.AQUA);
        creationList.append("Placed Blocks: ");
        // creationList.append(Color.WHITE);
        for (Entry<Integer, Integer> entry : creations.entrySet()) {
          creationList.append(Material.getMaterial(entry.getKey()));
          creationList.append(" (");
          creationList.append(entry.getValue());
          creationList.append("), ");
        }
        if (creationList.toString().contains(","))
          creationList.delete(creationList.lastIndexOf(","), creationList.length());
        StringBuilder brokenList = new StringBuilder();
        // brokenList.append(Color.RED);
        brokenList.append("Broken Blocks: ");
        // brokenList.append(Color.WHITE);
        for (Entry<Integer, Integer> entry : destructions.entrySet()) {
          brokenList.append(Material.getMaterial(entry.getKey()));
          brokenList.append(" (");
          brokenList.append(entry.getValue());
          brokenList.append("), ");
        }
        if (brokenList.toString().contains(","))
          brokenList.delete(brokenList.lastIndexOf(","), brokenList.length());
        StringBuilder explodeList = new StringBuilder();
        // brokenList.append(Color.RED);
        explodeList.append("Exploded Blocks: ");
        // brokenList.append(Color.WHITE);
        for (Entry<Integer, Integer> entry : explosions.entrySet()) {
          explodeList.append(Material.getMaterial(entry.getKey()));
          explodeList.append(" (");
          explodeList.append(entry.getValue());
          explodeList.append("), ");
        }
        if (explodeList.toString().contains(","))
          explodeList.delete(explodeList.lastIndexOf(","), explodeList.length());

        StringBuilder burnList = new StringBuilder();
        // brokenList.append(Color.RED);
        burnList.append("Burned Blocks: ");
        // brokenList.append(Color.WHITE);
        for (Entry<Integer, Integer> entry : burns.entrySet()) {
          burnList.append(Material.getMaterial(entry.getKey()));
          burnList.append(" (");
          burnList.append(entry.getValue());
          burnList.append("), ");
        }
        if (burnList.toString().contains(","))
          burnList.delete(burnList.lastIndexOf(","), burnList.length());
        for (Player player : players) {
          player.sendMessage(
              BigBrother.premessage + playerName + " has made " + size + " modifications");
          if (creations.entrySet().size() > 0) player.sendMessage(creationList.toString());
          if (destructions.entrySet().size() > 0) player.sendMessage(brokenList.toString());
          if (explosions.entrySet().size() > 0) player.sendMessage(explodeList.toString());
          if (burns.entrySet().size() > 0) player.sendMessage(burnList.toString());
        }
      } else {
        for (Player player : players) {
          player.sendMessage(
              BigBrother.premessage + playerName + " has no modifications in this area.");
        }
      }
    } catch (SQLException ex) {
      BigBrother.log.log(Level.SEVERE, "[BBROTHER]: Find SQL Exception", ex);
    } finally {
      try {
        if (rs != null) rs.close();
        if (ps != null) ps.close();
        if (conn != null) conn.close();
      } catch (SQLException ex) {
        BigBrother.log.log(Level.SEVERE, "[BBROTHER]: Find SQL Exception (on close)");
      }
    }
  }