public boolean select(String email) {

    con = (Connection) DBConnector.getConnection();

    try {
      String sql = "SELECT mail_address FROM user WHERE mail_address = ?";
      ps = (PreparedStatement) con.prepareStatement(sql);
      ps.setString(1, email);
      ResultSet rs = ps.executeQuery();
      if (rs.next()) {
        rs.getString(1);
        result = true;
      }
    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      if (con != null) {
        try {
          con.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
    }
    return result;
  }
  public List<Funcionario> list() {
    String sql = "SELECT * FROM FUNCIONARIO";
    Funcionario funcionario = null;

    try {
      PreparedStatement stmt = (PreparedStatement) connection.prepareStatement(sql);
      ResultSet rs = stmt.executeQuery();
      List<Funcionario> funcionarios = new ArrayList<Funcionario>();

      while (rs.next()) {
        funcionario = new Funcionario();
        funcionario.setNumFuncionario(rs.getInt("id_funcionario"));
        funcionario.setNomeFuncionario(rs.getString("nome_funcionario"));
        funcionario.setComissao(rs.getDouble("comissao"));
        funcionario.setEspecialidade(rs.getString("especialidade"));

        funcionarios.add(funcionario);
      }

      stmt.close();
      rs.close();

      return funcionarios;
    } catch (SQLException e) {
      throw new RuntimeException(e);
    }
  }
Beispiel #3
0
 public static int getNumeroExpulsiones(Alumno alumno, GregorianCalendar fecha) {
   int ret = 0;
   PreparedStatement st = null;
   ResultSet res = null;
   try {
     // Tenemos que ver si hay expulsiones para ese alumno
     st =
         (PreparedStatement)
             MaimonidesApp.getApplication()
                 .getConector()
                 .getConexion()
                 .prepareStatement(
                     "SELECT count(*) FROM expulsiones WHERE alumno_id=? AND fecha<=?");
     st.setInt(1, alumno.getId());
     st.setDate(2, new java.sql.Date(fecha.getTimeInMillis()));
     res = st.executeQuery();
     if (res.next()) {
       ret = res.getInt(1);
     }
   } catch (SQLException ex) {
     Logger.getLogger(Expulsion.class.getName()).log(Level.SEVERE, null, ex);
   }
   Obj.cerrar(st, res);
   return ret;
 }
Beispiel #4
0
 /**
  * Calcula si un alumno esta expulsado. Se sabe si un alumno está expulsado por el número de dias
  * escolares entre la fecha de expulsión y la de parte. Un día escolar es el numero de partes con
  * fecha distinta entre dos fechas.
  *
  * @param anoEscolar Año escola
  * @param alumno Alumno
  * @param fecha Fecha en la que se quiere saber si el alumno estça expulsado
  * @return true si está expulsado en la fecha del parte, false si no lo está
  */
 public static Boolean isAlumnoExpulsado(Alumno alumno, GregorianCalendar fecha) {
   boolean ret = false;
   try {
     // Tenemos que ver si hay expulsiones para ese alumno
     PreparedStatement st =
         (PreparedStatement)
             MaimonidesApp.getApplication()
                 .getConector()
                 .getConexion()
                 .prepareStatement("SELECT * FROM expulsiones WHERE alumno_id=? AND fecha<=?");
     st.setInt(1, alumno.getId());
     st.setDate(2, new java.sql.Date(fecha.getTimeInMillis()));
     ResultSet res = st.executeQuery();
     while (res.next() && !ret) {
       // Si hay expulsiones tenemos que ver si son válidas
       // Para eso tenemos que contar los partes desde la fecha de expulsión hasta ahora
       GregorianCalendar fechaExpulsion = Fechas.toGregorianCalendar(res.getDate("fecha"));
       if (fechaExpulsion != null) {
         // Como la fecha de expulsión esta incluida tenemos que quitarle un día
         fechaExpulsion.add(GregorianCalendar.DATE, -1);
         // Y vemos la diferencia en días
         int dias = res.getInt("dias");
         long diasTranscurridos =
             Fechas.getDiferenciaTiempoEn(fecha, fechaExpulsion, GregorianCalendar.DATE);
         ret = diasTranscurridos <= dias;
       }
     }
     Obj.cerrar(st, res);
   } catch (SQLException ex) {
     Logger.getLogger(Expulsion.class.getName()).log(Level.SEVERE, null, ex);
   }
   return ret;
 }
Beispiel #5
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();
 }
Beispiel #6
0
 public JasperPrint relatorioModalidade(String modalidade) throws Exception {
   java.sql.Connection con = ConexaoDB.getInstance().getCon();
   String nomeRelatorio = "br/sistcomp/sar/impressao/relatorioModalidade.jasper";
   URL urlFile = getClass().getClassLoader().getResource(nomeRelatorio);
   modalidade = (new StringBuilder()).append("= '").append(modalidade).append("'").toString();
   String query =
       (new StringBuilder())
           .append(
               "SELECT p.nome,a.matricula,m.nome "
                   + "AS modalidade FROM pessoas p INNER JOIN alunos a ON p.idPessoa = a.idPessoa"
                   + " INNER JOIN adesoes ad ON a.matricula = ad.matricula INNER JOIN planos pl on "
                   + "ad.codPlano = pl.`codPlano` INNER JOIN modalidades m ON pl.codModalidade = "
                   + "m.codModalidade WHERE m.nome ")
           .append(modalidade)
           .append(" ")
           .append(" ORDER BY p.nome")
           .toString();
   PreparedStatement stmt = (PreparedStatement) con.prepareStatement(query);
   ResultSet rs = stmt.executeQuery();
   JRResultSetDataSource jrRS = new JRResultSetDataSource(rs);
   java.util.Map parameters = new HashMap();
   JasperPrint rel = JasperFillManager.fillReport(urlFile.openStream(), parameters, jrRS);
   rs.close();
   stmt.close();
   return rel;
 }
  /**
   * retrieve food items from database
   *
   * @param type beverage or food , or null for combination
   * @return menu - list of items
   */
  public ArrayList<Item> getMenu(String type) {
    String sql = "SELECT itemName, price, description FROM Menu";
    if (type != null) {
      sql += " WHERE type=?";
    }
    try {
      PreparedStatement statement = (PreparedStatement) connection.prepareStatement(sql);
      if (type != null) {
        statement.setString(0, type);
      }
      ResultSet rs = statement.executeQuery();
      ArrayList<Item> menu = new ArrayList<Item>(); // maybe food menu if there is beverage menu
      while (rs.next()) {
        String itemName = rs.getString("itemName");
        double price = rs.getDouble("price");
        String desc = rs.getString("description");
        Item i = new Item(itemName, price, desc);
        menu.add(i);
      }
      rs.close();
      statement.close();
      return menu;

    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return null;
    }
  }
  /**
   * Get a customer by id
   *
   * @param id customer id
   * @return a customer
   */
  public Customer getACustomer(int id) {
    String sql = "Select * From Customer where cid = ?";

    try {

      PreparedStatement statement = (PreparedStatement) connection.prepareStatement(sql);
      statement.setInt(1, id);
      ResultSet rs = statement.executeQuery();

      if (rs.next()) {
        Customer customer = new Customer();
        customer.setEmail(rs.getString("email"));
        customer.setFirstName(rs.getString("firstName"));
        customer.setLastName(rs.getString("lastName"));
        customer.setId(rs.getInt("cid"));

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

        return customer;
      } else {
        return null;
      }

    } catch (SQLException e) {
      e.printStackTrace();
      System.out.println("Error at get a customer");
      return null;
    }
  }
  /**
   * Cancel a reservation
   *
   * @param email
   * @param d
   * @return
   */
  public boolean cancelReservation(String email, Date d) {
    boolean success = false;

    int cid = getCID(email);

    if (cid != -1) {
      String queryCancelReservation = "DELETE FROM Reservation WHERE cID=? AND reservationDate=?";
      try {
        PreparedStatement statement =
            (PreparedStatement) connection.prepareStatement(queryCancelReservation);
        statement.setInt(1, cid);
        statement.setDate(2, d);
        statement.execute();
        statement.close();
        success = true;

      } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        success = false;
        System.out.println("Failed: " + e.getMessage());
      } finally {

        return success;
      }
    } else {
      return false;
    }
  }
Beispiel #10
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;
  }
Beispiel #11
0
 @Override
 protected ArrayList<Usuario> doInBackground() {
   ArrayList<Usuario> ret = new ArrayList<Usuario>();
   if (!Beans.isDesignTime()) {
     try {
       PreparedStatement st =
           (PreparedStatement)
               MaimonidesApp.getApplication()
                   .getConector()
                   .getConexion()
                   .prepareStatement(
                       "SELECT * FROM usuarios WHERE fbaja IS NULL ORDER BY nombre");
       ResultSet res = st.executeQuery();
       while (res.next()) {
         Usuario p = new Usuario();
         try {
           p.cargarDesdeResultSet(res);
           ret.add(p);
         } catch (SQLException ex) {
           Logger.getLogger(PanelUsuarios.class.getName()).log(Level.SEVERE, null, ex);
         } catch (Exception ex) {
           Logger.getLogger(PanelUsuarios.class.getName()).log(Level.SEVERE, null, ex);
         }
       }
       Obj.cerrar(st, res);
     } catch (SQLException ex) {
       Logger.getLogger(PanelUsuarios.class.getName()).log(Level.SEVERE, null, ex);
     }
   }
   return ret; // return your result
 }
  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
Beispiel #13
0
 /**
  * @Description: 在源库中查找最新的预测计划,并保证期号在预测范围内,否则报错
  *
  * @author [email protected]
  * @date Feb 15, 2016 3:29:13 PM
  * @return
  */
 public Fast3SiMa getSiMaYuceRecordByIssueCode(String issueNumber) {
   Connection srcConn = ConnectSrcDb.getSrcConnection();
   PreparedStatement pstmt = null;
   Fast3SiMa data = null;
   String sql =
       "SELECT ID,YUCE_ISSUE_START,YUCE_ISSUE_STOP,DROWN_PLAN,DROWN_CYCLE,DROWN_ISSUE_NUMBER  FROM "
           + App.simaTbName
           + " WHERE "
           + issueNumber
           + " BETWEEN YUCE_ISSUE_START AND YUCE_ISSUE_STOP   ORDER BY ID DESC LIMIT 1";
   try {
     pstmt = (PreparedStatement) srcConn.prepareStatement(sql);
     ResultSet rs = pstmt.executeQuery();
     while (rs.next()) {
       data = new Fast3SiMa();
       data.setId(rs.getInt(1));
       data.setYuceIssueStart(rs.getString(2));
       data.setYuceIssueStop(rs.getString(3));
       data.setDrownPlan(rs.getString(4));
       data.setDrownCycle(rs.getInt(5));
       data.setDrownIssueNumber(rs.getString(6));
     }
     if (rs != null && !rs.isClosed()) {
       rs.close();
     }
   } catch (SQLException e) {
     LogUtil.error(e.getMessage(), "sima");
   }
   return data;
 }
Beispiel #14
0
 public void setAlumno(Alumno alumno) {
   this.alumno = null;
   lInfoAlumno.setText("");
   // De primeras ponemos todos los apoyos a false
   for (int hora = 0; hora < 6; hora++) {
     for (int dia = 0; dia < 5; dia++) {
       tabla.getModel().setValueAt(false, hora, dia + 1);
     }
   }
   // Sacamos todos sus apoyos
   if (alumno != null) {
     lInfoAlumno.setText(alumno.getNombreFormateado());
     try {
       String sql =
           "SELECT distinct h.dia,h.hora FROM horarios_ AS h JOIN apoyos_alumnos AS aa ON aa.horario_id=h.id WHERE aa.alumno_id=? ";
       PreparedStatement st =
           (PreparedStatement)
               MaimonidesApp.getApplication().getConector().getConexion().prepareStatement(sql);
       st.setInt(1, alumno.getId());
       ResultSet res = st.executeQuery();
       while (res.next()) {
         tabla.getModel().setValueAt(true, res.getInt("hora") - 1, res.getInt("dia"));
       }
       Obj.cerrar(st, res);
     } catch (SQLException ex) {
       Logger.getLogger(PanelApoyos.class.getName()).log(Level.SEVERE, null, ex);
     }
   }
   this.alumno = alumno;
 }
  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);
    }
  }
Beispiel #16
0
 /**
  * @Description: 在源库中查找最新的期号
  *
  * @author songjia
  * @date Feb 15, 2016 3:29:13 PM
  * @return
  */
 public SrcDataBean getRecordByIssueNumber(String issueNumber) {
   Connection srcConn = ConnectSrcDb.getSrcConnection();
   PreparedStatement pstmt = null;
   SrcDataBean srcDataBean = null;
   String sql =
       "SELECT issue_number,no1,no2,no3 FROM "
           + App.srcNumberTbName
           + " WHERE ISSUE_NUMBER = '"
           + issueNumber
           + "'";
   try {
     pstmt = (PreparedStatement) srcConn.prepareStatement(sql);
     ResultSet rs = pstmt.executeQuery();
     while (rs.next()) {
       srcDataBean = new SrcDataBean();
       srcDataBean.setIssueId(rs.getString(1));
       srcDataBean.setNo1(rs.getInt(2));
       srcDataBean.setNo2(rs.getInt(3));
       srcDataBean.setNo3(rs.getInt(4));
     }
     if (rs != null && !rs.isClosed()) {
       rs.close();
     }
   } catch (SQLException e) {
     LogUtil.error(e.getMessage(), "sima");
   }
   return srcDataBean;
 }
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String username = request.getParameter("contacts");

    String username_check = "";
    try {
      Connection conn = new Database().dbconnection();
      PreparedStatement ps =
          (PreparedStatement) conn.prepareStatement("select username from Users where username= ?");
      ps.setString(1, username);
      ResultSet rs = ps.executeQuery();
      while (rs.next()) {
        username_check = rs.getString("username");
      }
      conn.close();
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    if (username_check.equals(username) && username != "" && username != null) {

      String sender = request.getParameter("username");
      RequestDispatcher friendRequest =
          request.getRequestDispatcher(
              "/jsp/FriendRequestOut.jsp?sender=" + sender + "&reciver=" + username);

      friendRequest.forward(request, response);

    } else out.println("User is not registered");
  }
  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
  @Override
  public List<DamageItem> findAll() throws Exception {
    try {
      con = db.getConnect();
      String sql = "select * from damaged";
      PreparedStatement statement = (PreparedStatement) con.prepareStatement(sql);

      ResultSet result = statement.executeQuery();
      List<DamageItem> dl = new ArrayList<>();

      while (result.next()) {
        DamageItem di = new DamageItem();
        di.setId(result.getInt("id"));
        di.setItem(result.getString("item"));
        di.setQty(result.getInt("qty"));
        di.setReason(result.getString("reason"));
        di.setDate(result.getString("date"));
        di.setStaffstamp(result.getString("staffStamp"));

        dl.add(di);
      }
      return dl;
    } catch (Exception e) {
      // TODO: handle exception
      e.printStackTrace();
    }
    return null;
  }
  /**
   * Checks if the databasePassword is the same as the provided password.
   *
   * @param login
   * @param password
   * @return true / false
   * @throws InstantiationException
   * @throws IllegalAccessException
   * @throws ClassNotFoundException
   * @throws SQLException
   */
  public static boolean checkPassword(String login, String password)
      throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {

    String sql = "SELECT password FROM users WHERE login = ? ";
    String serverPassword = "";
    Boolean isValid = false;

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

    ps.setString(1, login);

    ResultSet rs = ps.executeQuery();

    if (rs.next()) {

      serverPassword = rs.getString("password");

      if (password.equals(serverPassword)) {
        isValid = true;
      }
    }

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

    return isValid;
  }
  public static void createConnection(int card_n, String arr[]) {
    Connection conn = null;
    PreparedStatement stmt = null;

    try {
      // STEP 2: Register JDBC driver
      Class.forName("com.mysql.jdbc.Driver");

      // STEP 3: Open a connection
      JOptionPane.showMessageDialog(null, "Connecting to a selected database...");

      conn = (Connection) DriverManager.getConnection(DB_URL, USER, PASS);
      JOptionPane.showMessageDialog(null, "Connected database successfully...");

      // STEP 4: Execute a query
      int flag = 0;

      try {
        String sql =
            "insert into registration (card_number,name,h_f_name,department,designation) values (?,?,?,?,?)";
        stmt = (PreparedStatement) conn.prepareStatement(sql);
        stmt.setInt(1, card_n);
        stmt.setString(2, arr[0]);
        stmt.setString(3, arr[1]);
        stmt.setString(4, arr[2]);
        stmt.setString(5, arr[3]);

        stmt.execute();
      } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Record not inerted. Duplicate entry!");
        flag = 1;
      }

      // stmt.executeUpdate(sql);
      if (flag == 0) JOptionPane.showMessageDialog(null, "Inserted record in table!..");

    } catch (SQLException se) {
      // Handle errors for JDBC
      se.printStackTrace();

    } catch (Exception e) {

      // Handle errors for Class.forName
      JOptionPane.showMessageDialog(null, "ERROR!");
      e.printStackTrace();
    } finally {
      // finally block used to close resources
      try {
        if (stmt != null) conn.close();
      } catch (SQLException se) {
      } // do nothing
      try {
        if (conn != null) conn.close();
      } catch (SQLException se) {
        se.printStackTrace();
      } // end finally try
    } // end try
    JOptionPane.showMessageDialog(null, "Goodbye!");
  } // end main
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    try {
      // create our mysql database connection

      String myUrl =
          "jdbc:mysql://biomedinformatics.is.umbc.edu/Alzheimer?autoReconnect=true&useSSL=false";

      Connection conn = DriverManager.getConnection(myUrl, "weijianqin", "weijianqin");

      // our SQL SELECT query.
      // if you only need a few columns, specify them by name instead of using "*"
      String query = "select Name,Alternate_Names,Accession_Id from PharmGKB_diseases";

      // create the java statement
      Statement st = conn.createStatement();

      // execute the query, and get a java resultset
      ResultSet rs = st.executeQuery(query);
      PreparedStatement pst_user =
          (PreparedStatement)
              conn.prepareStatement(
                  "INSERT INTO DiseaseSynonyms(Synonyms,Disease,Accession_Id) VALUES(?,?,?)");

      // iterate through the java resultset
      while (rs.next()) {

        if (rs.getString(2).length() > 0) {
          String disease = rs.getString("Name");
          String AN = term_split(rs.getString(2));
          String AI = rs.getString(3);
          // System.out.print(disease);

          String[] AN_arr = AN.split("&");

          // print the results

          for (String str : AN_arr) {
            // System.out.print(str);
            pst_user.setString(1, str);
            pst_user.setString(2, disease);
            pst_user.setString(3, AI);
            pst_user.execute();
          }

          // System.out.print("\n");

        }
      }
      st.close();
    } catch (Exception e) {
      System.err.println("Got an exception! ");
      System.err.println(e.getMessage());
    }
  }
Beispiel #23
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;
 }
Beispiel #24
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();
    }
  }
Beispiel #25
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);
   }
 }
Beispiel #26
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();
   }
 }
  /**
   * Rate a restaurant and give a feedback Rate uses SQL INSERT INTO
   *
   * @param stars number of stars
   * @param feedback user's feedback
   * @param customer a customer
   * @return true if rate works fine, false otherwise
   * @throws SQLException
   */
  public boolean rate(int stars, String feedback, Customer customer) throws SQLException {
    boolean success = false;
    PreparedStatement insertStatement = null;
    int customerID = getCID(customer.getEmail());
    String query =
        "INSERT INTO Rating (cid, stars, feedback) VALUES (?,?,?) "
            + "ON DUPLICATE KEY UPDATE stars=?, feedback=?";

    try {
      connection.setAutoCommit(false);
      insertStatement = (PreparedStatement) connection.prepareStatement(query);
      insertStatement.setInt(1, customerID);
      insertStatement.setInt(2, stars);
      insertStatement.setString(3, feedback);
      insertStatement.setInt(4, stars);
      insertStatement.setString(5, feedback);
      insertStatement.execute();

      connection.commit();
      success = true;

    } catch (SQLException e) {
      e.printStackTrace();
      success = false;
    } finally {
      if (insertStatement != null) {
        insertStatement.close();
      }

      connection.setAutoCommit(true);
      return success;
    }
  }
Beispiel #28
0
 public JasperPrint relatorioPlanosVencidos() throws Exception {
   java.sql.Connection con = ConexaoDB.getInstance().getCon();
   String nomeRelatorio = "br/sistcomp/sar/impressao/relatorioPlanosVencidos.jasper";
   URL urlFile = getClass().getClassLoader().getResource(nomeRelatorio);
   String query = "";
   PreparedStatement stmt = (PreparedStatement) con.prepareStatement(query);
   ResultSet rs = stmt.executeQuery();
   JRResultSetDataSource jrRS = new JRResultSetDataSource(rs);
   java.util.Map parameters = new HashMap();
   JasperPrint rel = JasperFillManager.fillReport(urlFile.openStream(), parameters, jrRS);
   rs.close();
   stmt.close();
   return rel;
 }
Beispiel #29
0
 public void insertDokter(Dokter d) throws SQLException {
   try {
     PreparedStatement ps = (PreparedStatement) connection.prepareStatement(insertDokter);
     ps.setString(1, d.getIdDokter());
     ps.setString(2, d.getNmDokter());
     ps.setString(3, d.getIdSpesialis());
     ps.executeUpdate();
     ps.close();
     //       JOptionPane.showMessageDialog(null, "Data dokter berhasil ditambah!");
   } catch (SQLException se) {
     //         JOptionPane.showMessageDialog(null, se.getMessage(),"Insert Dokter
     // Gagal!",JOptionPane.ERROR_MESSAGE);
   }
 }
Beispiel #30
0
 private String[] getMarketNames() {
   ArrayList<String> diffMarket = new ArrayList<String>();
   String query = DISTINCT_MARKET_NAME_QUERY;
   PreparedStatement pstmt;
   try {
     pstmt = (PreparedStatement) conn.prepareStatement(query);
     ResultSet rs = pstmt.executeQuery();
     while (rs.next()) {
       diffMarket.add(rs.getString("market_name"));
     }
   } catch (SQLException e) {
     e.printStackTrace();
   }
   return diffMarket.toArray(new String[diffMarket.size()]);
 }