public void accionSubirNivel(String usuario, String tipoUnidad) {
    String campo;
    if (tipoUnidad.equalsIgnoreCase("tecnologia")) campo = "nivel";
    else if (tipoUnidad.equalsIgnoreCase("arma")) campo = "arma";
    else campo = "armadura";

    try {
      Connection conn = Conectar.conectar();

      Statement st = conn.createStatement();

      st.executeQuery(
          "UPDATE usuarios SET "
              + campo
              + "=(SELECT "
              + campo
              + "+1 FROM usuarios WHERE nick='"
              + usuario
              + "') WHERE nick='"
              + usuario
              + "'");

      st.executeQuery("DELETE FROM investigaciones WHERE idInvestigacion = " + idConstruccion);

      st.executeQuery("commit");

      st.close();
      conn.close();

    } catch (SQLException ex) {
      System.out.println(
          ex.getMessage() + ex.getErrorCode() + " :: Fallo subir nivel investigacion");
    }
  }
 private void executeUpdate(Connection conn, String sql) throws SQLException {
   if (conn != null) {
     Statement stmt = conn.createStatement();
     stmt.executeUpdate(sql);
     stmt.close();
   }
 }
예제 #3
0
 public void dispose() {
   try {
     stmt.close();
     con.close();
   } catch (SQLException e) {
   }
 }
예제 #4
0
  public ExptLocatorTree(Genome g) {
    super();
    try {
      java.sql.Connection c = DatabaseFactory.getConnection(ExptLocator.dbRole);
      int species = g.getSpeciesDBID();
      int genome = g.getDBID();

      Statement s = c.createStatement();
      ResultSet rs = null;

      rs =
          s.executeQuery(
              "select e.name, e.version from experiment e, exptToGenome eg where e.active=1 and "
                  + "e.id=eg.experiment and eg.genome="
                  + genome);
      while (rs.next()) {
        String name = rs.getString(1);
        String version = rs.getString(2);
        ChipChipLocator loc = new ChipChipLocator(g, name, version);
        this.addElement(loc.getTreeAddr(), loc);
      }
      rs.close();

      rs =
          s.executeQuery(
              "select ra.name, ra.version from rosettaanalysis ra, rosettaToGenome rg where "
                  + "ra.id = rg.analysis and ra.active=1 and rg.genome="
                  + genome);
      while (rs.next()) {
        String name = rs.getString(1);
        String version = rs.getString(2);
        MSPLocator msp = new MSPLocator(g, name, version);
        this.addElement(msp.getTreeAddr(), msp);
      }
      rs.close();

      rs =
          s.executeQuery(
              "select ra.name, ra.version from bayesanalysis ra, bayesToGenome rg where "
                  + "ra.id = rg.analysis and ra.active=1 and rg.genome="
                  + genome);
      while (rs.next()) {
        String name2 = rs.getString(1);
        String version2 = rs.getString(2);
        ExptLocator loc2 = new BayesLocator(g, name2, version2);
        addElement(loc2.getTreeAddr(), loc2);
      }
      rs.close();
      s.close();

      DatabaseFactory.freeConnection(c);
    } catch (SQLException se) {
      se.printStackTrace(System.err);
      throw new RuntimeException(se);
    } catch (UnknownRoleException e) {
      e.printStackTrace();
    }
  }
예제 #5
0
  public void connectItems(String query)
        // PRE:  query must be initialized
        // POST: Updates the list of Items based on the query.
      {
    String driver = "org.apache.derby.jdbc.ClientDriver"; // Driver for DB
    String url = "jdbc:derby://localhost:1527/ShopDataBase"; // Url for DB
    String user = "******"; // Username for db
    String pass = "******"; // Password for db
    Connection myConnection; // Connection obj to db
    Statement stmt; // Statement to execute a result appon
    ResultSet results; // A set containing the returned results
    int rowcount; // Num objects in the resultSet
    int i; // Index for the array

    try { // Try connection to db

      Class.forName(driver).newInstance(); // Create our db driver

      myConnection = DriverManager.getConnection(url, user, pass); // Initalize our connection

      stmt =
          myConnection.createStatement(
              ResultSet.TYPE_SCROLL_INSENSITIVE,
              ResultSet.CONCUR_UPDATABLE); // Create a new statement
      results = stmt.executeQuery(query); // Store the results of our query

      rowcount = 0;
      if (results.last()) // Go to the last result
      {
        rowcount = results.getRow();
        results.beforeFirst();
      }
      itemsArray = new Item[rowcount];

      i = 0;
      while (results.next()) // Itterate through the results set
      {
        itemsArray[i] =
            new Item(
                results.getInt("item_id"),
                results.getString("item_name"),
                results.getString("item_type"),
                results.getInt("price"),
                results.getInt("owner_id"),
                results.getString("item_path")); // Creat new Item
        i++;
      }

      results.close(); // Close the ResultSet
      stmt.close(); // Close the statement
      myConnection.close(); // Close the connection to db

    } catch (Exception e) // Cannot connect to db
    {
      System.err.println(e.toString());
      System.err.println("Error, something went horribly wrong in connectItems!");
    }
  }
 private void close(Statement ps) {
   try {
     if (ps != null) {
       ps.close();
     }
   } catch (SQLException e) {
     LOGGER.error("error during closing:" + e.getMessage(), e);
   }
 }
예제 #7
0
  public void updateTables(String updateQuery1, String updateQuery2, String updateQuery3)
        // PRE:  updateQuery1,updateQuery2, updateQuery3 must be initialized
        // POST: Updates the list of Items based on the querys.
      {
    String driver = "org.apache.derby.jdbc.ClientDriver"; // Driver for DB
    String url = "jdbc:derby://localhost:1527/ShopDataBase"; // Url for DB
    String user = "******"; // Username for db
    String pass = "******"; // Password for db
    Connection myConnection; // Connection obj to db
    Statement stmt; // Statement to execute a result appon
    ResultSet results; // A set containing the returned results
    int i; // Index for the array
    try // Try connection to db
    {

      Class.forName(driver).newInstance(); // Create our db driver

      myConnection = DriverManager.getConnection(url, user, pass); // Initalize our connection

      stmt =
          myConnection.createStatement(
              ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
      stmt.executeUpdate(updateQuery1);

      stmt.executeUpdate(updateQuery2);

      stmt.executeUpdate(updateQuery3);

      results = stmt.executeQuery(previous_query); // Call the previous query

      i = 0;
      while (results.next()) // Itterate through the results set
      {
        itemsArray[i] =
            new Item(
                results.getInt("item_id"),
                results.getString("item_name"),
                results.getString("item_type"),
                results.getInt("price"),
                results.getInt("owner_id"),
                results.getString("item_path"));
        i++;
      }
      results.close(); // Close the ResultSet
      stmt.close(); // Close the statement
      myConnection.close(); // Close the connection to db

    } catch (Exception e) // Cannot connect to db
    {
      System.err.println(e.toString());
      System.err.println("Error, something went horribly wrong! in updateTables");
    }
  }
예제 #8
0
 public void closeDB() {
   try {
     if (statement != null) {
       statement.close();
     }
     if (db != null) {
       db.close();
     }
   } catch (Exception e) {
     System.out.println("Database could not closed");
     e.printStackTrace();
   }
 } // closeDB sonu
  public void actionPerformed(ActionEvent ae) {
    String str = ae.getActionCommand();
    if (str.equals("Ok")) {
      String str1 = (String) jcmname.getSelectedItem();

      Connection con = null;
      Statement stat = null;

      if (str1.equals("Pulsar")
          || str1.equals("CT 100")
          || str1.equals("Discover DTS-i")
          || str1.equals("Wave DTS-i")) {
        try {
          Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
          con = DriverManager.getConnection("Jdbc:Odbc:showroom");
          System.out.println("Got Connection :" + con);
          stat = con.createStatement();
          ResultSet rs = stat.executeQuery("select * from vehicle");
          System.out.println("chk1");
          while (rs.next()) {
            if (str1.equals(rs.getString(1))) {

              tfcap.setText("" + rs.getInt(2));
              tfeng.setText("" + rs.getInt(3));
              tfbhp.setText("" + rs.getInt(4));
              tfvolt.setText("" + rs.getInt(5));
              tfrpm.setText("" + rs.getInt(6));
              tfweight.setText("" + rs.getInt(7));
              tfgear.setText("" + rs.getInt(8));
            }
          }

          stat.close();
          con.close();

        } catch (Exception ex) {
        }

      } else {
        JOptionPane.showMessageDialog(
            null, "Please Choose Model Name", "Error", JOptionPane.ERROR_MESSAGE);
      }
    }

    if (str.equals("can")) {
      this.dispose();
      // new menu(1);
    }
  }
  /**
   * Fill the table using m_sql
   *
   * @param table table
   */
  private static void tableLoad(MiniTable table) {
    //	log.finest(m_sql + " - " +  m_groupBy);
    String sql =
        MRole.getDefault()
                .addAccessSQL(m_sql.toString(), "tab", MRole.SQL_FULLYQUALIFIED, MRole.SQL_RO)
            + m_groupBy
            + m_orderBy;

    log.finest(sql);
    try {
      Statement stmt = DB.createStatement();
      ResultSet rs = stmt.executeQuery(sql);
      table.loadTable(rs);
      stmt.close();
    } catch (SQLException e) {
      log.log(Level.SEVERE, sql, e);
    }
  } //  tableLoad
예제 #11
0
  public void login() {
    String driver = "oracle.jdbc.driver.OracleDriver";
    String url = "jdbc:oracle:thin:@localhost:1521:orcl";
    Connection con = null;
    Statement stmt = null;
    ResultSet rs = null;

    String id, pw, sql;
    try {
      Class.forName(driver);
      con = DriverManager.getConnection(url, "hr", "hr");
      stmt = con.createStatement();
      sql = "select * from chatuser where id = '" + lid.getText() + "'";
      rs = stmt.executeQuery(sql);
      if (rs.next()) {
        pw = rs.getString(2);
        nick = rs.getString(3);
        if (lpw.getText().equals(pw)) {
          jd.setVisible(false);
          setVisible(true);
        } else {
          lpw.setText("일치하지 않습니다.");
        }
      } else {
        lid.setText("일치하지 않습니다.");
      }
    } catch (Exception e1) {
      e1.printStackTrace();
      System.out.println("데이터 베이스 연결 실패!!");
    } finally {
      try {
        if (rs != null) rs.close();
        if (stmt != null) stmt.close();
        if (con != null) con.close();
      } catch (Exception e1) {
        System.out.println(e1.getMessage());
      }
    }
  }
예제 #12
0
  public void bookRoom() {
    try {
      int code = 0;
      Connection con =
          DriverManager.getConnection(
              "jdbc:mysql://67.20.111.85:3306/jeehtove_caliking?relaxAutoCommit=false",
              "jeehtove_ck",
              "Z_^PBBZT+kcy");
      Statement stmt_insert = con.createStatement();
      Statement stmt_tableRange = con.createStatement();
      Statement stmt_checkrooms = con.createStatement();
      Statement stmt_checkrooms_2 = con.createStatement();

      String insert = null;
      int flag = 0;

      String room_type;
      if (standardRoom.isSelected()) {
        room_type = "Standard";
        code = 1;
      } else if (familyRoom.isSelected()) {
        room_type = "Family";
        code = 2;
      } else {
        room_type = "Suite";
        code = 3;
      }

      // Converting string from checkin and checkout dates so that they can access the correct table
      String currentDate_checkin_getText = checkindateField.getText();
      String currentDate_checkin_rest = currentDate_checkin_getText.substring(5);
      String currentDate_checkin_replace = currentDate_checkin_rest.replace("-", "_");
      String currentDate_checkin_year = currentDate_checkin.substring(0, 4);
      String currentDate_checkin_final =
          currentDate_checkin_year + "_" + currentDate_checkin_replace;

      String currentDate_checkout_getText = checkoutdateField.getText();
      String currentDate_checkout_rest = currentDate_checkout_getText.substring(5);
      String currentDate_checkout_replace = currentDate_checkout_rest.replace("-", "_");
      String currentDate_checkout_year = currentDate_checkout.substring(0, 4);
      String currentDate_checkout_final =
          currentDate_checkout_year + "_" + currentDate_checkout_replace;

      // MySQL Statement to select tables from schema that are in between checkin and checkout range
      String tableRange =
          "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='jeehtove_caliking' AND TABLE_NAME BETWEEN 'rooms_"
              + currentDate_checkin_final
              + "' AND 'rooms_"
              + currentDate_checkout_final
              + "';";
      ResultSet tb_Range = stmt_tableRange.executeQuery(tableRange);

      System.out.println(tableRange);
      List tb_range_list = new ArrayList();

      while (tb_Range.next()) {
        String tb_range_date = tb_Range.getString("table_name");
        tb_range_list.add(tb_range_date);
        // String current_table = tb_Range.getString("table_name");
        // System.out.println(tb_range_list.add(tb_Range.getString("table_name")));
      }

      stmt_tableRange.close();

      for (int x = 0; x < tb_range_list.size(); x++) {
        String query_checkrooms =
            "SELECT * FROM "
                + tb_range_list.get(x)
                + " WHERE type = '"
                + code
                + "' AND booked = '0' LIMIT 1;";
        // System.out.println(query_checkrooms);
        ResultSet checkrooms = stmt_checkrooms.executeQuery(query_checkrooms);
        while (checkrooms.next()) {
          String getroomnumber = checkrooms.getString("room");
          insert =
              "INSERT INTO `reservations` VALUES ('"
                  + getroomnumber
                  + "', '"
                  + checkindateField.getText()
                  + "', '"
                  + checkoutdateField.getText()
                  + "',  '"
                  + room_type
                  + "',  '"
                  + nameField.getText()
                  + "');";
          String bookroom =
              "UPDATE `"
                  + tb_range_list.get(x)
                  + "` SET booked = '1' WHERE room = '"
                  + getroomnumber
                  + "';";
          // System.out.println(insert);
          int cr = stmt_checkrooms_2.executeUpdate(bookroom);
          flag = 1;
          System.out.println("Room Booked!");
        }
      }

      if (flag == 1) {
        int rs = stmt_insert.executeUpdate(insert);
      } else {
        System.out.println("All " + room_type + " rooms are booked for the time requested.");
      }

      /*String query_checkrooms = "SELECT * FROM rooms_" + currentDate_checkin_final + " WHERE type = '" + code + "' AND booked = '0';";
      System.out.println(query_checkrooms);
      Statement stmt_checkrooms = con.createStatement();
      ResultSet checkrooms = stmt_checkrooms.executeQuery(query_checkrooms);*/

      /*if (checkrooms.next()){
      		String getroomnumber = checkrooms.getString("room");
      		String insert = "INSERT INTO `reservations` VALUES ('" + getroomnumber + "', '" +  checkindateField.getText() + "', '" +  checkoutdateField.getText() + "',  '" + room_type + "',  '" + nameField.getText() + "');";
      		String bookroom = "UPDATE `rooms_" + currentDate_checkin_final + "` SET booked = '1' WHERE room = '" + getroomnumber + "';";
      //System.out.println(insert);
      	int rs=stmt_insert.executeUpdate(insert);
      	int cr=stmt_checkrooms.executeUpdate(bookroom);
      	con.commit();
      	System.out.println("Room Booked!");
      	}*/

      // else System.out.println("All " + room_type + " rooms are booked for the time requested.");
      System.out.println("Complete.");
    } catch (Exception e) {
      System.out.println(e);
    }
  }
  public void init(boolean force) {
    dbCount = -1;
    String version = null;
    Connection conn = null;
    ResultSet rs = null;
    Statement stmt = null;

    try {
      conn = getConnection();
    } catch (SQLException se) {
      final File dbFile = new File(dbDir + File.separator + dbName + ".data.db");
      final File dbDirectory = new File(dbDir);
      if (dbFile.exists()
          || (se.getErrorCode() == 90048)) { // Cache is corrupt or wrong version, so delete it
        FileUtils.deleteQuietly(dbDirectory);
        if (!dbDirectory.exists()) {
          LOGGER.debug(
              "The cache has been deleted because it was corrupt or had the wrong version");
        } else {
          if (!PMS.isHeadless()) {
            JOptionPane.showMessageDialog(
                (JFrame) (SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame())),
                String.format(Messages.getString("DLNAMediaDatabase.5"), dbDir),
                Messages.getString("Dialog.Error"),
                JOptionPane.ERROR_MESSAGE);
          }
          LOGGER.debug(
              "Damaged cache can't be deleted. Stop the program and delete the folder \""
                  + dbDir
                  + "\" manually");
          configuration.setUseCache(false);
          return;
        }
      } else {
        LOGGER.debug("Cache connection error: " + se.getMessage());
        configuration.setUseCache(false);
        return;
      }
    }

    try {
      conn = getConnection();

      stmt = conn.createStatement();
      rs = stmt.executeQuery("SELECT count(*) FROM FILES");
      if (rs.next()) {
        dbCount = rs.getInt(1);
      }
      rs.close();
      stmt.close();

      stmt = conn.createStatement();
      rs = stmt.executeQuery("SELECT VALUE FROM METADATA WHERE KEY = 'VERSION'");
      if (rs.next()) {
        version = rs.getString(1);
      }
    } catch (SQLException se) {
      if (se.getErrorCode()
          != 42102) { // Don't log exception "Table "FILES" not found" which will be corrected in
        // following step
        LOGGER.error(null, se);
      }
    } finally {
      close(rs);
      close(stmt);
      close(conn);
    }
    boolean force_reinit =
        !PMS.getVersion().equals(version); // here we can force a deletion for a specific version
    if (force || dbCount == -1 || force_reinit) {
      LOGGER.debug("Database will be (re)initialized");
      try {
        conn = getConnection();
        executeUpdate(conn, "DROP TABLE FILES");
        executeUpdate(conn, "DROP TABLE METADATA");
        executeUpdate(conn, "DROP TABLE REGEXP_RULES");
        executeUpdate(conn, "DROP TABLE AUDIOTRACKS");
        executeUpdate(conn, "DROP TABLE SUBTRACKS");
      } catch (SQLException se) {
        if (se.getErrorCode()
            != 42102) { // Don't log exception "Table "FILES" not found" which will be corrected in
          // following step
          LOGGER.error(null, se);
        }
      }
      try {
        StringBuilder sb = new StringBuilder();
        sb.append("CREATE TABLE FILES (");
        sb.append("  ID                INT AUTO_INCREMENT");
        sb.append(", FILENAME          VARCHAR2(1024)       NOT NULL");
        sb.append(", MODIFIED          TIMESTAMP            NOT NULL");
        sb.append(", TYPE              INT");
        sb.append(", DURATION          DOUBLE");
        sb.append(", BITRATE           INT");
        sb.append(", WIDTH             INT");
        sb.append(", HEIGHT            INT");
        sb.append(", SIZE              NUMERIC");
        sb.append(", CODECV            VARCHAR2(").append(SIZE_CODECV).append(")");
        sb.append(", FRAMERATE         VARCHAR2(").append(SIZE_FRAMERATE).append(")");
        sb.append(", ASPECT            VARCHAR2(").append(SIZE_ASPECT).append(")");
        sb.append(", ASPECTRATIOCONTAINER    VARCHAR2(")
            .append(SIZE_ASPECTRATIO_CONTAINER)
            .append(")");
        sb.append(", ASPECTRATIOVIDEOTRACK   VARCHAR2(")
            .append(SIZE_ASPECTRATIO_VIDEOTRACK)
            .append(")");
        sb.append(", REFRAMES          TINYINT");
        sb.append(", AVCLEVEL          VARCHAR2(").append(SIZE_AVC_LEVEL).append(")");
        sb.append(", BITSPERPIXEL      INT");
        sb.append(", THUMB             BINARY");
        sb.append(", CONTAINER         VARCHAR2(").append(SIZE_CONTAINER).append(")");
        sb.append(", MODEL             VARCHAR2(").append(SIZE_MODEL).append(")");
        sb.append(", EXPOSURE          INT");
        sb.append(", ORIENTATION       INT");
        sb.append(", ISO               INT");
        sb.append(", MUXINGMODE        VARCHAR2(").append(SIZE_MUXINGMODE).append(")");
        sb.append(", FRAMERATEMODE     VARCHAR2(").append(SIZE_FRAMERATE_MODE).append(")");
        sb.append(", constraint PK1 primary key (FILENAME, MODIFIED, ID))");
        executeUpdate(conn, sb.toString());
        sb = new StringBuilder();
        sb.append("CREATE TABLE AUDIOTRACKS (");
        sb.append("  FILEID            INT              NOT NULL");
        sb.append(", ID                INT              NOT NULL");
        sb.append(", LANG              VARCHAR2(").append(SIZE_LANG).append(")");
        sb.append(", FLAVOR            VARCHAR2(").append(SIZE_FLAVOR).append(")");
        sb.append(", NRAUDIOCHANNELS   NUMERIC");
        sb.append(", SAMPLEFREQ        VARCHAR2(").append(SIZE_SAMPLEFREQ).append(")");
        sb.append(", CODECA            VARCHAR2(").append(SIZE_CODECA).append(")");
        sb.append(", BITSPERSAMPLE     INT");
        sb.append(", ALBUM             VARCHAR2(").append(SIZE_ALBUM).append(")");
        sb.append(", ARTIST            VARCHAR2(").append(SIZE_ARTIST).append(")");
        sb.append(", SONGNAME          VARCHAR2(").append(SIZE_SONGNAME).append(")");
        sb.append(", GENRE             VARCHAR2(").append(SIZE_GENRE).append(")");
        sb.append(", YEAR              INT");
        sb.append(", TRACK             INT");
        sb.append(", DELAY             INT");
        sb.append(", MUXINGMODE        VARCHAR2(").append(SIZE_MUXINGMODE).append(")");
        sb.append(", BITRATE           INT");
        sb.append(", constraint PKAUDIO primary key (FILEID, ID))");
        executeUpdate(conn, sb.toString());
        sb = new StringBuilder();
        sb.append("CREATE TABLE SUBTRACKS (");
        sb.append("  FILEID            INT              NOT NULL");
        sb.append(", ID                INT              NOT NULL");
        sb.append(", LANG              VARCHAR2(").append(SIZE_LANG).append(")");
        sb.append(", FLAVOR            VARCHAR2(").append(SIZE_FLAVOR).append(")");
        sb.append(", TYPE              INT");
        sb.append(", constraint PKSUB primary key (FILEID, ID))");

        executeUpdate(conn, sb.toString());
        executeUpdate(
            conn,
            "CREATE TABLE METADATA (KEY VARCHAR2(255) NOT NULL, VALUE VARCHAR2(255) NOT NULL)");
        executeUpdate(conn, "INSERT INTO METADATA VALUES ('VERSION', '" + PMS.getVersion() + "')");
        executeUpdate(conn, "CREATE INDEX IDXARTIST on AUDIOTRACKS (ARTIST asc);");
        executeUpdate(conn, "CREATE INDEX IDXALBUM on AUDIOTRACKS (ALBUM asc);");
        executeUpdate(conn, "CREATE INDEX IDXGENRE on AUDIOTRACKS (GENRE asc);");
        executeUpdate(conn, "CREATE INDEX IDXYEAR on AUDIOTRACKS (YEAR asc);");
        executeUpdate(
            conn,
            "CREATE TABLE REGEXP_RULES ( ID VARCHAR2(255) PRIMARY KEY, RULE VARCHAR2(255), ORDR NUMERIC);");
        executeUpdate(conn, "INSERT INTO REGEXP_RULES VALUES ( '###', '(?i)^\\W.+', 0 );");
        executeUpdate(conn, "INSERT INTO REGEXP_RULES VALUES ( '0-9', '(?i)^\\d.+', 1 );");

        // Retrieve the alphabet property value and split it
        String[] chars = Messages.getString("DLNAMediaDatabase.1").split(",");

        for (int i = 0; i < chars.length; i++) {
          // Create regexp rules for characters with a sort order based on the property value
          executeUpdate(
              conn,
              "INSERT INTO REGEXP_RULES VALUES ( '"
                  + chars[i]
                  + "', '(?i)^"
                  + chars[i]
                  + ".+', "
                  + (i + 2)
                  + " );");
        }

        LOGGER.debug("Database initialized");
      } catch (SQLException se) {
        LOGGER.info("Error in table creation: " + se.getMessage());
      } finally {
        close(conn);
      }
    } else {
      LOGGER.debug("Database file count: " + dbCount);
      LOGGER.debug("Database version: " + version);
    }
  }
예제 #14
0
  public void accionInsertarEdificio(int idReg, int idUni) { // aqui se ejecuta el estamento
    try { // de insertar edificios
      Connection conn = Conectar.conectar();

      Statement st = conn.createStatement(); // añade 1
      System.out.println(idReg + "    " + idUni);
      st.executeQuery(
          "INSERT INTO edificiosregion VALUES (" + idReg + ", " + idUni + ", " + 1 + ")");

      if (cuentaatras == 0
          && cantidad > 0) // y decrementa las tareas pendientes en la base de datos
      st.executeQuery(
            "UPDATE construcciones SET cantidad = (SELECT cantidad-1 FROM construcciones WHERE idConstruccion = "
                + idConstruccion
                + ") WHERE idConstruccion = "
                + idConstruccion);

      if (cuentaatras == 0 && cantidad == 0) {
        System.out.println(idConstruccion);
        st.executeQuery("DELETE FROM construcciones WHERE idConstruccion = " + idConstruccion);
      }

      st.executeQuery("commit");

      st.close();
      conn.close();

    } catch (SQLException ex) {
      System.out.println(
          ex.getMessage() + ex.getErrorCode() + " :: Fallo de conexion del temporizador");

      if (ex.getErrorCode() == 00001) {
        Connection conn;
        try {
          conn = Conectar.conectar();
          // Si no se ha podido ejecutar la insercion porque la clave ya existe, se actualiza la
          // tabla
          Statement st = conn.createStatement();
          st.executeQuery(
              "UPDATE edificiosregion SET cantidad = (SELECT cantidad+1 FROM edificiosregion WHERE idRegion = "
                  + idReg
                  + "AND idEdificio = "
                  + idUni
                  + ") WHERE idRegion = "
                  + idReg
                  + " AND idEdificio = "
                  + idUni);

          if (cuentaatras == 0
              && cantidad > 0) // y decrementa las tareas pendientes en la base de datos
          st.executeQuery(
                "UPDATE construcciones SET cantidad = (SELECT cantidad-1 FROM construcciones WHERE idConstruccion = "
                    + idConstruccion
                    + ") WHERE idConstruccion = "
                    + idConstruccion);

          if (cuentaatras == 0 && cantidad == 0) {
            System.out.println(idConstruccion);
            st.executeQuery("DELETE FROM construcciones WHERE idConstruccion = " + idConstruccion);
          }

          st.executeQuery("commit");

          st.close();
          conn.close();

        } catch (SQLException ex1) {
          System.out.println(ex1.getMessage() + " :: Fallo en catch de insertar");
        }
      }
    }
  }
예제 #15
0
  public void accionEjecutarMovimiento() {
    try {
      Connection conn = Conectar.conectar();

      Statement st = conn.createStatement();

      ResultSet rs =
          st.executeQuery("SELECT propietario FROM regiones WHERE idRegion = " + idRegionDestino);
      String propietario = "nulo";
      if (rs.next()) {
        propietario = rs.getString(1);
      }

      // Si el territorio esta
      // vacio****************************************************************************
      if (propietario.equalsIgnoreCase("Deshabitado")) {
        String nombre = generaNombre();

        st.executeQuery(
            "UPDATE regiones SET nombreRegion = '"
                + nombre
                + "', propietario = '"
                + usuario
                + "' WHERE idRegion = "
                + idRegionDestino);
        st.executeQuery(
            "INSERT INTO edificiosregion VALUES ("
                + idRegionDestino
                + ", "
                + 1400
                + ", "
                + 1
                + ")");
        for (int i = 0; i < pelotones.size(); i = i + 2) {
          st.executeQuery(
              "INSERT INTO despliegues VALUES ("
                  + idRegionDestino
                  + ", "
                  + pelotones.get(i)
                  + ", "
                  + pelotones.get(i + 1)
                  + ")");
        }
        st.executeQuery("DELETE movimientos WHERE idTropa = " + idTropa);
        st.executeQuery("commit");

        System.out.println("Query ejecutado.");
      }

      // Si el territorio te pertenece
      // *******************************************************************************
      else if (propietario.equalsIgnoreCase(usuario)) {
        ResultSet rs2 =
            st.executeQuery("select * from despliegues where idRegion = " + idRegionDestino);
        ArrayList<Despliegue> despliegues = new ArrayList<Despliegue>();
        while (rs2.next()) {
          despliegues.add(new Despliegue(rs2.getInt(1), rs2.getInt(2), rs2.getInt(3)));
        }
        Boolean encontrado = false;

        for (int i = 0; i < pelotones.size(); i = i + 2) {
          encontrado = false;

          for (Despliegue despliegue : despliegues) {
            if (pelotones.get(i).equals(despliegue.getIdUnidad())) {
              st.executeQuery(
                  "update despliegues set cantidad = "
                      + (despliegue.getCantidad() + pelotones.get(i + 1))
                      + " where idRegion = "
                      + idRegionDestino
                      + " and idUnidad = "
                      + despliegue.getIdUnidad());
              encontrado = true;
            }
          }
          if (!encontrado) {
            st.executeQuery(
                "INSERT INTO despliegues VALUES ("
                    + idRegionDestino
                    + ", "
                    + pelotones.get(i)
                    + ", "
                    + pelotones.get(i + 1)
                    + ")");
          }
        }
        st.executeQuery("DELETE movimientos WHERE idTropa = " + idTropa);
        st.executeQuery("commit");

        System.out.println("Query ejecutado.");
        rs2.close();
      }

      // Si es un territorio enemigo ( COMBATE )
      // *****************************************************************************
      else {
        int ataque = 0;
        int defensa = 0;
        int defenemiga = 0;
        int ataenemigo = 0;

        SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy HH:mm");
        java.util.Date fecha = new java.util.Date();
        String fechahora = formato.format(fecha);

        // Recolectamos el ataque y la defensa del enemigo
        ResultSet rs3 =
            st.executeQuery("select * from despliegues where idRegion = " + idRegionDestino);
        ArrayList<Despliegue> despliegues = new ArrayList<Despliegue>();
        while (rs3.next()) {
          despliegues.add(new Despliegue(rs3.getInt(1), rs3.getInt(2), rs3.getInt(3)));
        }

        for (Despliegue despliegue : despliegues) {
          if (despliegue.getIdUnidad() == 4100) {
            ataenemigo = ataenemigo + (15 * despliegue.getCantidad());
            defenemiga = defenemiga + (30 * despliegue.getCantidad());
          } else if (despliegue.getIdUnidad() == 4101) {
            ataenemigo = ataenemigo + (25 * despliegue.getCantidad());
            defenemiga = defenemiga + (50 * despliegue.getCantidad());
          } else if (despliegue.getIdUnidad() == 4102) {
            ataenemigo = ataenemigo + (55 * despliegue.getCantidad());
            defenemiga = defenemiga + (20 * despliegue.getCantidad());
          } else if (despliegue.getIdUnidad() == 4103) {
            ataenemigo = ataenemigo + 800;
            ataenemigo = ataenemigo * ((ataenemigo * 10) / 100);
            defenemiga = defenemiga + 600;
          } else if (despliegue.getIdUnidad() == 4104) {
            ataenemigo = ataenemigo + (400 * despliegue.getCantidad());
            defenemiga = defenemiga + (100 * despliegue.getCantidad());
          } else if (despliegue.getIdUnidad() == 4102) {
            ataenemigo = ataenemigo + (50 * despliegue.getCantidad());
            defenemiga = defenemiga + (800 * despliegue.getCantidad());
          }
        }

        // Recolectamos informacion de edificios defensivos
        ResultSet rs4 =
            st.executeQuery("select * from edificiosregion where idRegion = " + idRegionDestino);
        ArrayList<EdificiosRegion> despliegues2 = new ArrayList<EdificiosRegion>();
        while (rs4.next()) {
          despliegues2.add(new EdificiosRegion(rs4.getInt(1), rs4.getInt(2), rs4.getInt(3)));
        }

        for (EdificiosRegion despliegue2 : despliegues2) {
          if (despliegue2.idEdificio == 1300) {
            ataenemigo = ataenemigo + (200 * despliegue2.cantidad);
            defenemiga = defenemiga + (1000 * despliegue2.cantidad);
          } else if (despliegue2.idEdificio == 1301) {
            ataenemigo = ataenemigo + (500 * despliegue2.cantidad);
            defenemiga = defenemiga + (500 * despliegue2.cantidad);
          }
        }

        // Recolectamos ataque y defensa nuestra***************************
        for (int i = 0; i < pelotones.size(); i = i + 2) {
          if (pelotones.get(i) == 4100) {
            ataque = ataque + (15 * pelotones.get(i + 1));
            defensa = defensa + (30 * pelotones.get(i + 1));
          } else if (pelotones.get(i) == 4101) {
            ataque = ataque + (25 * pelotones.get(i + 1));
            defensa = defensa + (50 * pelotones.get(i + 1));
          } else if (pelotones.get(i) == 4102) {
            ataque = ataque + (55 * pelotones.get(i + 1));
            defensa = defensa + (20 * pelotones.get(i + 1));
          } else if (pelotones.get(i) == 4103) {
            ataque = ataque + 800;
            ataque = ataque * ((ataenemigo * 10) / 100);
            defensa = defensa + 600;
          } else if (pelotones.get(i) == 4104) {
            ataque = ataque + (400 * pelotones.get(i + 1));
            defensa = defensa + (100 * pelotones.get(i + 1));
          } else if (pelotones.get(i) == 4100) {
            ataque = ataque + (50 * pelotones.get(i + 1));
            defensa = defensa + (800 * pelotones.get(i + 1));
          }
        }

        int ataque1 = defenemiga - ataque;
        int ataque2 = defensa - ataenemigo;
        // Capturamos el nick del enemigo***************
        String enemigo = "Deshabitado";
        ResultSet rsenemigo =
            st.executeQuery("select propietario from regiones where idRegion = " + idRegionDestino);
        if (rsenemigo.next()) {
          enemigo = rsenemigo.getString(1);
        }

        // 1 ---  Si el enemigo tiene vida inferior a 0 y tu no
        if (ataque1 <= 0 && ataque2 > 0) {
          // Se conquista el territorio, se compra aldea y se recolocan las unidades sobrantes
          // dependiendo del ataque 2

          st.executeQuery(
              "UPDATE regiones SET propietario = '"
                  + usuario
                  + "' WHERE idRegion = "
                  + idRegionDestino);

          st.executeQuery(
              "DELETE edificiosregion WHERE idRegion = "
                  + idRegionDestino
                  + " AND idEdificio != "
                  + 1400);

          st.executeQuery("DELETE despliegues WHERE idRegion = " + idRegionDestino);

          st.executeQuery("DELETE construcciones WHERE idRegion = " + idRegionDestino);

          st.executeQuery("DELETE movimientos WHERE idTropa = " + idTropa);

          // Escribimos un mensaje al usuario con los resultados de la batalla
          st.executeQuery(
              "INSERT INTO mensajes VALUES (s_mensajes.NEXTVAL, 'System', '"
                  + usuario
                  + "', 'Informe de Batalla', '"
                  + "¡Enhorabuena!#Has ganado la batalla en el territorio ["
                  + idRegionDestino
                  + "].#Daño Recibido-> "
                  + ataenemigo
                  + ".#Daño causado-> "
                  + ataque
                  + ".', '"
                  + fechahora
                  + "')");

          // Escribimos un mensaje al enemigo con los resultados de la batalla
          st.executeQuery(
              "INSERT INTO mensajes VALUES (s_mensajes.NEXTVAL, 'System', '"
                  + enemigo
                  + "', 'Informe de Batalla', '"
                  + "Lo siento.#Has perdido la batalla en el territorio ["
                  + idRegionDestino
                  + "].#Daño Recibido-> "
                  + ataque
                  + ".#Daño causado-> "
                  + ataenemigo
                  + ".', '"
                  + fechahora
                  + "')");

          System.out.println(ataque2);
          // Algoritmo para ver el porcentaje de unidades que me quedan
          int porcperdido = (int) (ataque2 * 100) / defensa;

          for (int i = 0; i < pelotones.size(); i = i + 2) {
            pelotones.set(i + 1, (int) (pelotones.get(i + 1) * porcperdido) / 100);
          }
          for (int i = 0; i < pelotones.size(); i = i + 2) {
            st.executeQuery(
                "INSERT INTO despliegues VALUES ("
                    + idRegionDestino
                    + ", "
                    + pelotones.get(i)
                    + ", "
                    + pelotones.get(i + 1)
                    + ")");
          }
        }

        // 2 --- Los 2 tienen la vida a 0 o menos
        else if (ataque1 <= 0 && ataque2 <= 0) {
          // El enemigo se queda con el territorio pero pierde todos los edificios y se recolocan
          // unidades dependiendo de ataque1.

          st.executeQuery(
              "DELETE edificiosregion WHERE idRegion = "
                  + idRegionDestino
                  + " AND idEdificio != "
                  + 1400);

          st.executeQuery("DELETE movimientos WHERE idTropa = " + idTropa);

          st.executeQuery("DELETE despliegues WHERE idRegion = " + idRegionDestino);

          // Escribimos un mensaje al usuario con los resultados de la batalla
          st.executeQuery(
              "INSERT INTO mensajes VALUES (s_mensajes.NEXTVAL, 'System', '"
                  + usuario
                  + "', 'Informe de Batalla', '"
                  + "Lo siento.#Has perdido la batalla en el territorio ["
                  + idRegionDestino
                  + "].#Daño Recibido-> "
                  + ataenemigo
                  + ".#Daño causado-> "
                  + ataque
                  + ".', '"
                  + fechahora
                  + "')");

          // Escribimos un mensaje al enemigo con los resultados de la batalla
          st.executeQuery(
              "INSERT INTO mensajes VALUES (s_mensajes.NEXTVAL, 'System', '"
                  + enemigo
                  + "', 'Informe de Batalla', '"
                  + "¡Enhorabuena!#Has conseguido defender tu territorio ubicado en ["
                  + idRegionDestino
                  + "].#"
                  + "Aunque has perdido todas tus tropas y edificios.#Daño Recibido-> "
                  + ataque
                  + ".#Daño causado-> "
                  + ataenemigo
                  + ".', '"
                  + fechahora
                  + "')");
        }

        // 3 -- Tu pierdes la batalla
        else if (ataque1 > 0 && ataque2 <= 0) {
          // El enemigo recoloca unidades y tu lo pierdes todo
          st.executeQuery("DELETE movimientos WHERE idTropa = " + idTropa);

          int porcperdido = (int) (ataque1 * 100) / defenemiga;

          for (Despliegue despliegue : despliegues) {
            despliegue.setCantidad((int) (despliegue.getCantidad() * porcperdido) / 100);
          }
          for (Despliegue despliegue : despliegues) {
            st.executeQuery(
                "UPDATE despliegues SET cantidad = "
                    + despliegue.getCantidad()
                    + " WHERE idRegion = "
                    + idRegionDestino
                    + " AND idUnidad = "
                    + despliegue.getIdUnidad());
          }

          // Escribimos un mensaje al usuario con los resultados de la batalla
          st.executeQuery(
              "INSERT INTO mensajes VALUES (s_mensajes.NEXTVAL, 'System', '"
                  + usuario
                  + "', 'Informe de Batalla', '"
                  + "Lo siento.#Has perdido la batalla en el territorio ["
                  + idRegionDestino
                  + "].#Daño Recibido-> "
                  + ataenemigo
                  + ".#Daño causado-> "
                  + ataque
                  + ".', '"
                  + fechahora
                  + "')");

          // Escribimos un mensaje al enemigo con los resultados de la batalla
          st.executeQuery(
              "INSERT INTO mensajes VALUES (s_mensajes.NEXTVAL, 'System', '"
                  + enemigo
                  + "', 'Informe de Batalla', '"
                  + "¡Enhorabuena!#Has conseguido defender tu territorio ubicado en ["
                  + idRegionDestino
                  + "].#Daño Recibido-> "
                  + ataque
                  + ".#Daño causado-> "
                  + ataenemigo
                  + ".', '"
                  + fechahora
                  + "')");

        }
        // 4 --- Los 2 quedan con vida**************************************************************
        else if (ataque1 > 0 && ataque2 > 0) {
          // Se recolocan unidades en los 2.

          st.executeQuery("DELETE movimientos WHERE idTropa = " + idTropa);

          int porcperdido1 = (int) (ataque1 * 100) / defenemiga;

          for (Despliegue despliegue : despliegues) {
            despliegue.setCantidad((int) (despliegue.getCantidad() * porcperdido1) / 100);
          }
          for (Despliegue despliegue : despliegues) {
            st.executeQuery(
                "UPDATE despliegues SET cantidad = "
                    + despliegue.getCantidad()
                    + " WHERE idRegion = "
                    + idRegionDestino
                    + " AND idUnidad = "
                    + despliegue.getIdUnidad());
          }

          int porcperdido2 = (int) (ataque2 * 100) / defensa;

          for (int i = 0; i < pelotones.size(); i = i + 2) {
            pelotones.set(i + 1, (int) (pelotones.get(i + 1) * porcperdido2) / 100);
          }
          for (int i = 0; i < pelotones.size(); i = i + 2) {
            st.executeQuery(
                "UPDATE despliegues SET cantidad = (SELECT cantidad+"
                    + pelotones.get(i + 1)
                    + " FROM despliegues WHERE idRegion = "
                    + idRegion
                    + " AND idUnidad = "
                    + pelotones.get(i)
                    + ") WHERE idRegion = "
                    + idRegion
                    + " AND idUnidad = "
                    + pelotones.get(i));
          }

          // Escribimos un mensaje al usuario con los resultados de la batalla
          st.executeQuery(
              "INSERT INTO mensajes VALUES (s_mensajes.NEXTVAL, 'System', '"
                  + usuario
                  + "', 'Informe de Batalla', '"
                  + "Lo siento.#Has perdido la batalla en la region ["
                  + idRegionDestino
                  + "].#"
                  + "Aunque has recuperado algunas unidades.#Daño Recibido-> "
                  + ataenemigo
                  + ".#Daño causado-> "
                  + ataque
                  + ".', '"
                  + fechahora
                  + "')");

          // Escribimos un mensaje al enemigo con los resultados de la batalla
          st.executeQuery(
              "INSERT INTO mensajes VALUES (s_mensajes.NEXTVAL, 'System', '"
                  + enemigo
                  + "', 'Informe de Batalla', '"
                  + "¡Enhorabuena!#Has conseguido defender tu territorio ubicado en ["
                  + idRegionDestino
                  + "].#Daño Recibido-> "
                  + ataque
                  + ".#Daño causado-> "
                  + ataenemigo
                  + ".', '"
                  + fechahora
                  + "')");
        }

        st.executeQuery("commit");
        rs3.close();
        rs4.close();
        rsenemigo.close();
      }

      st.close();
      rs.close();
      conn.close();
    } catch (SQLException e) {
      System.out.println(e.getMessage() + " Fallo ejecutar movimiento.");
    }
  }