Ejemplo n.º 1
0
 private void setValorApoyo(int dia, int hora, Boolean val) {
   if (val == null || !val) {
     // Borramos la asignacion
     String sql =
         "DELETE apoyos_alumnos FROM apoyos_alumnos JOIN horarios AS h ON h.id=apoyos_alumnos.horario_id WHERE apoyos_alumnos.alumno_id=? AND h.hora=? AND h.dia=?";
     try {
       PreparedStatement st =
           (PreparedStatement)
               MaimonidesApp.getApplication().getConector().getConexion().prepareStatement(sql);
       st.setInt(1, getAlumno().getId());
       st.setInt(2, hora);
       st.setInt(3, dia);
       st.executeUpdate();
     } catch (SQLException ex) {
       Logger.getLogger(PanelApoyos.class.getName()).log(Level.SEVERE, null, ex);
     }
   } else {
     // Creamos la asignacion
     String sql =
         "INSERT INTO apoyos_alumnos SELECT distinct ?, h.id FROM horarios_ AS h WHERE h.hora=? AND h.dia=? AND h.unidad_id=? ";
     try {
       PreparedStatement st =
           (PreparedStatement)
               MaimonidesApp.getApplication().getConector().getConexion().prepareStatement(sql);
       st.setInt(1, getAlumno().getId());
       st.setInt(2, hora);
       st.setInt(3, dia);
       st.setInt(4, getAlumno().getUnidad().getId());
       st.executeUpdate();
     } catch (SQLException ex) {
       Logger.getLogger(PanelApoyos.class.getName()).log(Level.SEVERE, null, ex);
     }
   }
 }
Ejemplo n.º 2
0
 @Override
 public boolean guardar() {
   boolean ret = false;
   try {
     String sql = "UPDATE expulsiones SET ano=?,alumno_id=?,fecha=?,dias=? WHERE id=?";
     if (getId() == null) {
       sql = "INSERT INTO expulsiones (ano,alumno_id,fecha,dias,id) VALUES(?,?,?,?,?)";
     }
     PreparedStatement st =
         (PreparedStatement)
             MaimonidesApp.getApplication()
                 .getConector()
                 .getConexion()
                 .prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
     st.setInt(1, getAnoEscolar().getId());
     st.setInt(2, getAlumno().getId());
     st.setDate(3, new java.sql.Date(getFecha().getTimeInMillis()));
     st.setInt(4, getDias());
     st.setObject(5, getId());
     ret = st.executeUpdate() > 0;
     if (ret && getId() == null) {
       setId((int) st.getLastInsertID());
     }
     st.close();
     ret = true;
   } catch (SQLException ex) {
     Logger.getLogger(Conducta.class.getName())
         .log(Level.SEVERE, "Error guardando datos de expulsion: " + this, ex);
   }
   return ret;
 }
  private void jbutLogActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_jbutLogActionPerformed

    if (jtxtUser.getText().equals("")) {
      JOptionPane.showMessageDialog(this, "Enter Details");
      return;
    }
    if (jtxtPass.getText().equals("")) {
      JOptionPane.showMessageDialog(this, "Enter Details");
      return;
    }

    try {
      DBConnection bConnection = new DBConnection();
      Connection con = bConnection.connect();
      Statement stm = con.createStatement();

      PreparedStatement s1 =
          (PreparedStatement) con.prepareStatement("Insert into login values(?,?,?)");
      s1.setString(1, jtxtUser.getText());
      s1.setString(2, jtxtPass.getText());
      s1.setString(3, (String) jComboBox1.getSelectedItem());

      int save = s1.executeUpdate();
      JOptionPane.showMessageDialog(this, "Data Saved Successfully!!");
      Clear();
    } catch (Exception ee) {
      System.out.println(ee.getMessage());
      JOptionPane.showMessageDialog(this, ee.getMessage());
    }
  } // GEN-LAST:event_jbutLogActionPerformed
  /**
   * Reserve a table
   *
   * @param partySize number of people in a party
   * @param d reservation date
   * @param tID table id
   * @param c a customer
   * @return true if succeed, false otherwise
   */
  public boolean reserveTable(int partySize, Date d, int tID, Customer c) {
    PreparedStatement statement = null;
    int customerid = getCID(c.getEmail());
    String sql_reserve =
        "INSERT INTO Restaurant.Reservation (reservationDate,partySize,cID,tID) values(?, ?, ?,?)";

    try {
      connection.setAutoCommit(false);
      statement = (PreparedStatement) connection.prepareStatement(sql_reserve);
      statement.setDate(1, d);
      statement.setInt(2, partySize);
      statement.setInt(3, customerid);
      statement.setInt(4, tID);
      statement.executeUpdate();
      connection.commit();

      if (statement != null) {
        statement.close();
      }

      connection.setAutoCommit(true);

      return true;

    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      System.out.println("Failed: " + e.getMessage());
      return false;
    }
  }
Ejemplo n.º 5
0
  /**
   * Inserts a new entry in the `session` table.
   *
   * @param id I
   * @param root
   * @return A unique key associated with the user
   * @throws InstantiationException
   * @throws IllegalAccessException
   * @throws ClassNotFoundException
   * @throws SQLException
   */
  public static String insertSession(int id, boolean root)
      throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {

    /* SESSION_HOUR_DURATIONS starting from now */
    Timestamp expires =
        new Timestamp(System.currentTimeMillis() + SESSION_HOUR_DURATION * 60 * 60 * 1000);

    String key = generateKey();

    String sql =
        "INSERT INTO `session` " + "(`key`, `user_id`, `expires`, `root`)" + " VALUE(?,?,?,?)";

    Connection connection = DataBaseUtils.getMySQLConnection();
    PreparedStatement ps = (PreparedStatement) connection.prepareStatement(sql);

    ps.setString(1, key);
    ps.setInt(2, id);
    ps.setTimestamp(3, expires);
    ps.setBoolean(4, root);

    ps.executeUpdate();

    System.out.println("Session inserted for id : " + id);

    ps.close();
    connection.close();

    return key;
  }
  @Override
  public boolean update(DamageItem d) throws Exception {
    String sql =
        "update damaged  set item = ?, qty = ?, reason = ? , date = ? , staffStamp = ? where id = "
            + d.getId();
    try {
      con = db.getConnect();

      PreparedStatement statement = (PreparedStatement) con.prepareStatement(sql);
      statement.setString(1, d.getItem());
      statement.setInt(2, d.getQty());
      statement.setString(3, d.getReason());
      statement.setString(4, d.getDate());
      statement.setString(5, d.getStaffstamp());
      statement.executeUpdate();

      return true;

    } catch (Exception e) {

      e.printStackTrace();

      return false;
    }
  }
Ejemplo n.º 7
0
  public static void dbUpdate(Creative creative) throws Exception {

    Connection conn = null;
    PreparedStatement statement = null;

    try {
      Class.forName("com.mysql.jdbc.Driver").newInstance();

      conn = DriverManager.getConnection("database_url", "username", "password");

      String query =
          "update creative set creativeID = ? , "
              + "creativeTimeStamp = ? "
              + "where creativeName = ?";
      statement = (PreparedStatement) conn.prepareStatement(query);
      statement.setString(1, creative.getCreativeID());
      statement.setString(2, creative.getCreativeTimestamp());
      statement.setString(3, creative.getName());
      statement.executeUpdate();
    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      statement.close();
      conn.close();
    }
  }
  private void jButton3ActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_jButton3ActionPerformed
    try {
      DBConnection bConnection = new DBConnection();
      Connection con = bConnection.connect();
      Statement stm = con.createStatement();

      if (jtxtUser.getText().equals("")) {
        JOptionPane.showMessageDialog(this, "Enter Details");
        return;
      }

      PreparedStatement s1 =
          (PreparedStatement)
              con.prepareStatement("delete from login where strUser='******'");
      int delete = s1.executeUpdate();

      JOptionPane.showMessageDialog(this, "User Deleted!!");
      Clear();
    } catch (Exception ee) {
      System.out.println(ee.getMessage());
    }

    // TODO add your handling code here:
  } // GEN-LAST:event_jButton3ActionPerformed
Ejemplo n.º 9
0
  public void setExcluir(ClassConecta conexao) {

    try {
      // ClassConecta conexao = new ClassConecta();

      // conexao.conecta();

      String comando =
          " DELETE FROM tipos_fornecedores  " + " 	WHERE " + " 	COD_TIPO_FORNECEDOR = ?  ";

      PreparedStatement stmt = (PreparedStatement) ClassConecta.con.prepareStatement(comando);
      // Formatar data Prevista

      stmt.setInt(1, getCod_tipo_fornecedor());

      stmt.executeUpdate();

      // System.out.println("Transação Concluída");
      JOptionPane.showMessageDialog(
          null, "O REGISTRO foi excluído com sucesso.", "ATENÇÃO", JOptionPane.INFORMATION_MESSAGE);
    } catch (Exception e) {
      System.err.println("Erro na Transação\n" + e);
      JOptionPane.showMessageDialog(
          null, "Erro na Transação", "ATENÇÃO", JOptionPane.ERROR_MESSAGE);
    }
  }
Ejemplo n.º 10
0
 /**
  * @param issueNumber
  * @param fast3CountList
  * @throws SQLException 四码预测插入预测计划方法
  */
 private void insertData2Db(String issueNumber, List<Fast3Count> fast3CountList)
     throws SQLException {
   Connection conn = ConnectSrcDb.getSrcConnection();
   String sql =
       "insert into "
           + App.simaTbName
           + " (YUCE_ISSUE_START,YUCE_ISSUE_STOP,DROWN_PLAN,CREATE_TIME) values(?,?,?,?)";
   String code1 = App.getNextIssueByCurrentIssue(issueNumber);
   String code2 = App.getNextIssueByCurrentIssue(code1);
   String code3 = App.getNextIssueByCurrentIssue(code2);
   int[] numArr = {
     fast3CountList.get(0).getNumber(),
     fast3CountList.get(1).getNumber(),
     fast3CountList.get(2).getNumber(),
     fast3CountList.get(3).getNumber()
   };
   Arrays.sort(numArr);
   PreparedStatement pstmt = (PreparedStatement) conn.prepareStatement(sql);
   pstmt.setString(1, code1);
   pstmt.setString(2, code3);
   pstmt.setString(
       3,
       Integer.toString(numArr[0])
           + Integer.toString(numArr[1])
           + Integer.toString(numArr[2])
           + Integer.toString(numArr[3]));
   pstmt.setTimestamp(4, new java.sql.Timestamp(new Date().getTime()));
   pstmt.executeUpdate();
 }
Ejemplo n.º 11
0
  // TODO
  public int insertCert(ApkBean apk) {
    int ret = -1;
    for (CertBean cert : apk.certs) {
      try {
        PreparedStatement pstmt = null;
        String marketUpdateQuery =
            "INSERT INTO cert " + "(issuer,certhash,certBrief)" + " VALUES(?, ?,?) ";
        pstmt = (PreparedStatement) conn.prepareStatement(marketUpdateQuery);
        pstmt.setString(
            1, ((X509Certificate) cert.certificate).getIssuerX500Principal().toString());
        pstmt.setString(2, cert.certificateHash);
        pstmt.setString(3, apk.certInfo());

        pstmt.executeUpdate();
        ret = 0;
      } catch (SQLException e) {
        if (e.getErrorCode() == 1062) {
          return 0;
        }
        e.printStackTrace();
        ret = -2;
      }
    }

    return ret;
  }
Ejemplo n.º 12
0
 private void validateAdd(RentalSchema p) {
   // TODO: Aqui se anade la data a la tabla de RentMovie
   try {
     String query =
         "INSERT INTO rentmovie (MoviesID, CustomersID, Rented, RentedOn, ReturnedOn)"
             + "VALUES (?, ?, ?, ?, ?)";
     ////////////
     Class.forName("com.mysql.jdbc.Driver"); // MySQL database connection
     Connection conn =
         (Connection)
             DriverManager.getConnection(
                 "jdbc:mysql://us-cdbr-azure-east-a.cloudapp.net:3306/movierental?"
                     + "user=b80812adafee28&password=5b6f9d25");
     PreparedStatement pst = (PreparedStatement) conn.prepareStatement(query);
     //////////////////////////////
     pst.setInt(1, p.getMoviesId());
     pst.setInt(2, p.getCustomersId());
     pst.setBoolean(3, true);
     pst.setString(4, p.getRentedOn());
     pst.setString(5, "Not yet Returned!");
     JOptionPane.showMessageDialog(null, "Data was saved sccessfully");
     pst.executeUpdate();
     conn.close();
   } catch (ClassNotFoundException | SQLException e) {
     JOptionPane.showMessageDialog(
         null, "There was some problem with the connection. Please try again!");
     e.printStackTrace();
   }
 }
Ejemplo n.º 13
0
 public void deleteDokter(String idDokter) throws SQLException {
   try {
     PreparedStatement ps = (PreparedStatement) connection.prepareStatement(deleteDokter);
     ps.setString(1, idDokter);
     ps.executeUpdate();
     ps.close();
     //  JOptionPane.showMessageDialog(null, "Data dokter berhasil dihapus!");
   } catch (SQLException se) {
     //  JOptionPane.showMessageDialog(null, se.getMessage(),"Delete Dokter
     // Gagal!",JOptionPane.ERROR_MESSAGE);
   }
 }
  public boolean updateSucess(
      int Id,
      String Date,
      String Own_project,
      String Money,
      String Borrow_object,
      String Pay_way,
      String Government_buystyle,
      String Government_buysite,
      String ProofID,
      String Contract_special,
      String Summary,
      String Haber_subject,
      String Project_manage,
      String Government_buyway,
      String Government_buyclassify,
      String IsSubmit) {
    Conn conn = new Conn();
    try {
      Connection connection = conn.getConnection(null);
      // PreparedStatement psmt=(PreparedStatement) connection.prepareStatement("update finance set
      // isSubmit=? where id=?");
      PreparedStatement psmt =
          (PreparedStatement)
              connection.prepareStatement(
                  "update  finance set date=? ,own_project=? ,money=? ,borrow_object=? ,pay_way=? ,government_buystyle=? ,government_buysite=? ,contract_special=? ,summary=? ,haber_subject=?, project_manage=?, government_buyway=?, government_buyclassify=? ,isSubmit=? where proofID=? ");
      psmt.setString(1, Date);
      psmt.setString(2, Own_project);
      psmt.setString(3, Money);
      psmt.setString(4, Borrow_object);
      psmt.setString(5, Pay_way);
      psmt.setString(6, Government_buystyle);
      psmt.setString(7, Government_buysite);

      psmt.setString(8, Contract_special);
      psmt.setString(9, Summary);
      psmt.setString(10, Haber_subject);
      psmt.setString(11, Project_manage);
      psmt.setString(12, Government_buyway);
      psmt.setString(13, Government_buyclassify);
      psmt.setString(14, IsSubmit);
      psmt.setString(15, ProofID);
      int i = psmt.executeUpdate();
      System.out.println(i);
      System.out.println(Id);
      System.out.println(Summary);

    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return true;
  }
Ejemplo n.º 15
0
  public void resetLocks(String marketName) {
    try {
      PreparedStatement pstmt;
      pstmt = (PreparedStatement) conn.prepareStatement(RESET_ID_LOCK_QUERY);
      pstmt.setString(1, marketName);
      pstmt.execute();

      pstmt.executeUpdate();
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 16
0
 public void updateDokter(Dokter d, String idDokter) throws SQLException {
   try {
     PreparedStatement ps = (PreparedStatement) connection.prepareStatement(updateDokter);
     ps.setString(1, d.getNmDokter());
     ps.setString(2, d.getIdSpesialis());
     ps.setString(3, idDokter);
     ps.executeUpdate();
     ps.close();
     //     JOptionPane.showMessageDialog(null, "Data dokter berhasil diubah!");
   } catch (SQLException se) {
     //    JOptionPane.showMessageDialog(null, se.getMessage(),"Update Dokter
     // Gagal!",JOptionPane.ERROR_MESSAGE);
   }
 }
Ejemplo n.º 17
0
 public void lockIds(String marketName, String[] ids, boolean isLocked) {
   try {
     PreparedStatement pstmt;
     pstmt = (PreparedStatement) conn.prepareStatement(LOCK_IDS_QUERY);
     for (String id : ids) {
       pstmt.setBoolean(1, isLocked);
       pstmt.setString(2, marketName);
       pstmt.setString(3, id);
       pstmt.executeUpdate();
     }
   } catch (SQLException e) {
     e.printStackTrace();
   }
 }
  /**
   * upDate the sensor with new start and end time and also enabled/disabled information in Database
   *
   * @param sensor
   */
  public static void updateSensor(Sensor sensor) {
    System.out.println("Update sensor " + sensor.toString());
    try {
      conn =
          DriverManager.getConnection(
              "jdbc:mysql://localhost/sosecurity?" + "user=ssuser&password=sspwd");
      try {
        // String getSensor = "UPDATE sensor SET subAreaID=2, userID=1,
        // isArmed = true WHERE sensorID=1";
        String updateSubArea =
            "UPDATE sensor SET subAreaID= ? , userID= ?, isArmed=?, start_time=?, end_time= ? "
                + "WHERE sensorID=?";
        System.out.println(updateSubArea);
        PreparedStatement preparedStmt = (PreparedStatement) conn.prepareStatement(updateSubArea);
        preparedStmt.setInt(1, sensor.getSubAreaID());
        preparedStmt.setLong(2, sensor.getUserID());
        preparedStmt.setBoolean(3, sensor.getIsArmed());
        preparedStmt.setDate(4, new java.sql.Date(sensor.getFromTime().getTime()));
        if (sensor.getToDate() == null) {
          preparedStmt.setDate(5, null);
        } else {
          preparedStmt.setDate(5, new java.sql.Date(sensor.getToDate().getTime()));
        }
        preparedStmt.setInt(6, sensor.getSensorID());

        // execute the java prepared statement
        int affectedRow = preparedStmt.executeUpdate();
        System.out.println(affectedRow);
      } finally {
        // It's important to close the connection when you are done with
        // it
        try {
          conn.close();
        } catch (Throwable ignore) {
          /*
           * Propagate the original exception instead of this one that
           * you may want just logged
           */
          ignore.printStackTrace();
        }
      }
    } catch (SQLException ex) {
      // handle any errors
      System.out.println("SQLException: " + ex.getMessage());
      System.out.println("SQLState: " + ex.getSQLState());
      System.out.println("VendorError: " + ex.getErrorCode());
    }
    return;
  }
Ejemplo n.º 19
0
 /**
  * @param status
  * @throws SQLException 更新胆码表状态内容
  */
 private void updateDanMaStatus(Fast3SiMa fast3SiMa) throws SQLException {
   Connection conn = ConnectSrcDb.getSrcConnection();
   String sql =
       "UPDATE "
           + App.simaTbName
           + " SET DROWN_ISSUE_NUMBER=?,DROWN_NUMBER=?,status = ?,DROWN_CYCLE=?  where ID = ?";
   // System.out.println(sql);
   PreparedStatement pstmt = (PreparedStatement) conn.prepareStatement(sql);
   pstmt.setString(1, fast3SiMa.getDrownIssueNumber());
   pstmt.setString(2, fast3SiMa.getDrownNumber());
   pstmt.setString(3, fast3SiMa.getStatus());
   pstmt.setInt(4, fast3SiMa.getDrownCycle());
   pstmt.setInt(5, fast3SiMa.getId());
   pstmt.executeUpdate();
 }
Ejemplo n.º 20
0
  /**
   * Removes the entry associated with id, from the `sessions` table.
   *
   * @param id user id
   * @throws InstantiationException
   * @throws IllegalAccessException
   * @throws ClassNotFoundException
   * @throws SQLException
   */
  public static void removeSession(String key)
      throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {

    String sql = "DELETE FROM session WHERE `key`=?";

    Connection connection = DataBaseUtils.getMySQLConnection();
    PreparedStatement ps = (PreparedStatement) connection.prepareStatement(sql);

    ps.setString(1, key);
    ps.executeUpdate();

    System.out.println("Session removed for key : " + key);

    ps.close();
    connection.close();
  }
Ejemplo n.º 21
0
  /**
   * Deletes the user from the data-base.
   *
   * @param id user id
   * @return true | false
   * @throws SQLException
   * @throws ClassNotFoundException
   * @throws IllegalAccessException
   * @throws InstantiationException
   */
  public static void removeUserFromDataBase(int id)
      throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {

    String sql = "DELETE FROM users WHERE `id`=?";

    Connection connection = DataBaseUtils.getMySQLConnection();
    PreparedStatement ps = (PreparedStatement) connection.prepareStatement(sql);

    ps.setInt(1, id);
    ps.executeUpdate();

    System.out.println("User removed for id : " + id);

    ps.close();
    connection.close();
  }
  @Override
  public boolean delete(DamageItem d) throws Exception {
    String sql = "DELETE FROM damaged where id = ?";
    try {
      con = db.getConnect();
      PreparedStatement st = (PreparedStatement) con.prepareStatement(sql);
      st.setInt(1, d.getId());
      st.executeUpdate();

      System.out.println("deleted");
      return true;

    } catch (Exception e) {
      e.printStackTrace();
    }
    return false;
  }
Ejemplo n.º 23
0
  public void initIdLib(String marketName, String[] ids) {
    PreparedStatement pstmt;
    try {
      pstmt = (PreparedStatement) conn.prepareStatement(EMPTY_ID_LIB_QUERY);
      pstmt.setString(1, marketName);
      pstmt.execute();

      pstmt = (PreparedStatement) conn.prepareStatement(INIT_ID_LIB_QUERY);
      for (String id : ids) {
        pstmt.setString(1, marketName);
        pstmt.setString(2, id);
        pstmt.executeUpdate();
      }
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 24
0
  public void delete(VehicleType vehicleType) throws RARException {
    String deleteVTSql = "delete from VehicleType where vehicleTypeId = ?";
    PreparedStatement stmt = null;
    int inscnt;

    if (!vehicleType
        .isPersistent()) // is the VehicleType object persistent?  If not, nothing to actually
                         // delete
    return;

    try {
      stmt = (PreparedStatement) conn.prepareStatement(deleteVTSql);
      stmt.setLong(1, vehicleType.getId());
      inscnt = stmt.executeUpdate();
      if (inscnt == 1) {
        return;
      } else throw new RARException("VehicleTypeManager.delete: failed to delete a VehcleType");
    } catch (SQLException e) {
      e.printStackTrace();
      throw new RARException("VehicleTypeManager.delete: failed to delete a VehicleType: " + e);
    }
  }
  /**
   * Updates the subArea with the fireAlarm or Sensor when enabled or disabled
   *
   * @param sa
   */
  public static void updateSubArea(subArea sa) {
    try {
      System.out.println("Here !!!");
      conn =
          DriverManager.getConnection(
              "jdbc:mysql://localhost/sosecurity?" + "user=ssuser&password=sspwd");
      try {
        // String getSensor = "UPDATE sensor SET subAreaID=2, userID=1,
        // isArmed = true WHERE sensorID=1";
        String updateSubArea = "UPDATE subArea SET hasSensor= ?, hasFire=? WHERE subAreaID=?";
        System.out.println(updateSubArea);
        PreparedStatement preparedStmt = (PreparedStatement) conn.prepareStatement(updateSubArea);
        preparedStmt.setBoolean(1, sa.getHasSensor());
        preparedStmt.setBoolean(2, sa.getHasFire());
        preparedStmt.setInt(3, sa.getSubAreaID());

        // execute the java prepared statement
        int affectedRow = preparedStmt.executeUpdate();
        System.out.println(affectedRow);
      } finally {
        // It's important to close the connection when you are done with
        // it
        try {
          conn.close();
        } catch (Throwable ignore) {
          /*
           * Propagate the original exception instead of this one that
           * you may want just logged
           */
        }
      }
    } catch (SQLException ex) {
      // handle any errors
      System.out.println("SQLException: " + ex.getMessage());
      System.out.println("SQLState: " + ex.getSQLState());
      System.out.println("VendorError: " + ex.getErrorCode());
    }
    return;
  }
Ejemplo n.º 26
0
  /**
   * Adds a new username to the data-base.
   *
   * @param login username
   * @param password password
   * @param email email
   * @return true / false
   * @throws SQLException
   * @throws ClassNotFoundException
   * @throws IllegalAccessException
   * @throws InstantiationException
   */
  public static boolean addUserToDataBase(String login, String password, String email)
      throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {

    String sql = "INSERT INTO users " + "(login, password, email)" + " VALUES (?, ?, ?)";

    Boolean isAdded = false;

    Connection connection = DataBaseUtils.getMySQLConnection();
    PreparedStatement ps = (PreparedStatement) connection.prepareStatement(sql);

    ps.setString(1, login);
    ps.setString(2, password);
    ps.setString(3, email);
    ps.executeUpdate();

    isAdded = true;

    ps.close();
    connection.close();

    System.out.println("User Added To Database");
    return isAdded;
  }
  private void jbutCloseActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_jbutCloseActionPerformed
    if (jtxtPass.getText().equals("")) {
      JOptionPane.showMessageDialog(this, "Enter Details");
      return;
    }
    if (jtxtUser.getText().equals("")) {
      JOptionPane.showMessageDialog(this, "Enter Details");
      return;
    }

    try {
      DBConnection bConnection = new DBConnection();
      Connection con = bConnection.connect();
      Statement stm = con.createStatement();

      PreparedStatement s1 =
          (PreparedStatement)
              con.prepareStatement(
                  "update login set strPass='******',strType='"
                      + (String) jComboBox1.getSelectedItem()
                      + ""
                      + "' where strUser='******'");
      int update = s1.executeUpdate();
      JOptionPane.showMessageDialog(this, "Data Successfully Updated!!");
      Clear();
    } catch (Exception ee) {
      System.out.println(ee.getMessage());
    }

    // TODO add your handling code here:
  } // GEN-LAST:event_jbutCloseActionPerformed
Ejemplo n.º 28
0
  public void setAlterar(ClassConecta conexao) {

    try {
      // ClassConecta conexao = new ClassConecta();

      // conexao.conecta();

      String comando =
          "UPDATE tipos_fornecedores "
              + " 	SET                         "
              + " 	TIPO_FORNECEDOR = ?,        "
              + " 	GRUPO = ?,                  "
              + " 	OBS = ?                     "
              + " 	WHERE "
              + " 	COD_TIPO_FORNECEDOR = ?";

      System.out.println("Executando operação...");

      PreparedStatement stmt = (PreparedStatement) ClassConecta.con.prepareStatement(comando);

      stmt.setString(1, getTipo_fornecedor());
      stmt.setString(2, getGrupo());
      stmt.setString(3, getObs());
      stmt.setInt(4, getCod_tipo_fornecedor());

      stmt.executeUpdate();

      System.out.println("Transação Concluída");
      JOptionPane.showMessageDialog(
          null, "O REGISTRO foi salvo com sucesso.", "ATENÇÃO", JOptionPane.INFORMATION_MESSAGE);
    } catch (Exception e) {
      System.err.println("Erro na Transação\n" + e);
      JOptionPane.showMessageDialog(
          null, "Erro na Transação", "ATENÇÃO", JOptionPane.ERROR_MESSAGE);
    }
  }
Ejemplo n.º 29
0
  // TODO
  public int insertApk(ApkBean apk) {
    int ret = -1;
    if (apk.marketBean.marketName == null
        || apk.packageName == null
        || apk.packageName == null
        || apk.marketBean.marketAppName == null
        || apk.versionCode == 0
        || apk.versionName == null) return ret;
    // Update market database
    try {
      PreparedStatement pstmt = null;
      String marketUpdateQuery =
          "INSERT INTO market_"
              + apk.marketBean.marketName.trim().toLowerCase()
              + "(package_name,"
              + "version_code,"
              + "update_time,"
              + "app_name,"
              + "download_url,"
              + "p_id)"
              + " VALUES( ?, ?, CURDATE(), ?, ?, ?) ON DUPLICATE KEY UPDATE check_times= check_times+1";
      pstmt = (PreparedStatement) conn.prepareStatement(marketUpdateQuery);
      pstmt.setString(1, apk.packageName.trim());
      pstmt.setInt(2, apk.versionCode);
      pstmt.setString(3, apk.marketBean.marketAppName.trim());
      pstmt.setString(4, apk.marketBean.marketDownloadUrl.trim());
      pstmt.setString(5, apk.marketBean.marketPid.trim());

      pstmt.executeUpdate();
      ret = 0;
    } catch (SQLException e) {
      e.printStackTrace();
      ret = -2;
    }
    return ret;
  }
Ejemplo n.º 30
0
  public void save(VehicleType vehicleType) throws RARException {
    String insertVTSql = "insert into VehicleType ( typeName  ) values ( ? )";
    String updateVTSql = "update VehicleTye set typeName = ? where id = ?";
    PreparedStatement stmt = null;
    int inscnt;
    long VTId;

    /*
    if( club.getFounderId() == -1 )
        throw new ClubsException( "ClubManager.save: Attempting to save a Club without a founder" );
        */
    try {

      if (!vehicleType.isPersistent())
        stmt = (PreparedStatement) conn.prepareStatement(insertVTSql);
      else stmt = (PreparedStatement) conn.prepareStatement(updateVTSql);

      if (vehicleType.getType() != null) // type is unique and non null
        // This is me setting the value in col typeName in table VehicleType to the provided value
        stmt.setString(1, vehicleType.getType());
      else
        throw new RARException("VehicleTypeManager.save: can't save a VehicleType: name undefined");
      /*
       * This is an example for when there are more parameters to deal with
                  if( club.getAddress() != null )
                      stmt.setString( 2, club.getAddress() );
                  else
                      stmt.setNull( 2, java.sql.Types.VARCHAR );

                  if( club.getEstablishedOn() != null ) {
                      java.util.Date jDate = club.getEstablishedOn();
                      java.sql.Date sDate = new java.sql.Date( jDate.getTime() );
                      stmt.setDate( 3,  sDate );
                  }
                  else
                      stmt.setNull(3, java.sql.Types.DATE);

                  if( club.getFounder() != null && club.getFounder().isPersistent() )
                      stmt.setLong( 4, club.getFounder().getId() );
                  else
                      throw new ClubsException( "ClubManager.save: can't save a Club: founder is not set or not persistent" );
      */
      if (vehicleType.isPersistent()) stmt.setLong(2, vehicleType.getId());

      inscnt = stmt.executeUpdate();

      if (!vehicleType.isPersistent()) {
        if (inscnt >= 1) {
          String sql = "select last_insert_id()";
          if (stmt.execute(sql)) { // statement returned a result

            // retrieve the result
            ResultSet r = stmt.getResultSet();

            // we will use only the first row!
            //
            while (r.next()) {

              // retrieve the last insert auto_increment value
              VTId = r.getLong(1);
              if (VTId > 0) vehicleType.setId(VTId); // set this vehicleType's db id (proxy object)
            }
          }
        } else throw new RARException("VehicleTypeManager.save: failed to save a VehicleType");
      } else {
        if (inscnt < 1)
          throw new RARException("VehicleTypeManager.save: failed to save a VehicleType");
      }
    } catch (SQLException e) {
      e.printStackTrace();
      throw new RARException("VehicleTypeManager.save: failed to save a VehicleType: " + e);
    }
  }