예제 #1
0
public JTable queryTable(String table, String query) {

	//create statement
	Statement stmt = con.createStatement();
	stmt.executeUpdate(table);

	//query db for table
	ResultSet rs = stmt.executeQuery(query);

	//initialize values for jtable
	Object[50][50] data;
	int n=1;
	int p=1;

	//put info into jtable
	while (rs.next()) { // print up to 50 rows

	while (n<=50) { // print up to 50 columns
		String s = rs.getString(n);
		data[p][n] = s;
		}

	n=1;
	p++;
	}

	//create jtable
	String[] columnNames = {query};
	final JTable jtable = new JTable(data, columnNames);

	return jtable;
}
예제 #2
0
  @Override
  public void actionPerformed(ActionEvent axnEve) {
    Object obj = axnEve.getSource();
    if (obj == replyBut) {
      try {
        if (Home.composeDial != null && Home.composeDial.isShowing()) {

        } else {
          Home.composeDial =
              new ComposeMailDialog(
                  msgID, workingSet.getString("mail_addresses"), workingSet.getString("subject"));
        }
      } catch (SQLException sqlExc) {
        sqlExc.printStackTrace();
      }
    } else if (obj == forwardBut) {
      try {
        if (Home.composeDial != null && Home.composeDial.isShowing()) {

        } else {
          Home.composeDial =
              new ComposeMailDialog(
                  msgID,
                  workingSet.getString("subject") + "\n\n" + workingSet.getString("content"));
        }
      } catch (SQLException sqlExc) {
        sqlExc.printStackTrace();
      }
    }
  }
 public ArrayList<File> getFiles(String sql) {
   ArrayList<File> list = new ArrayList<File>();
   Connection conn = null;
   ResultSet rs = null;
   PreparedStatement ps = null;
   try {
     conn = getConnection();
     ps =
         conn.prepareStatement(
             sql.toLowerCase().startsWith("select")
                 ? sql
                 : ("SELECT FILENAME, MODIFIED FROM FILES WHERE " + sql));
     rs = ps.executeQuery();
     while (rs.next()) {
       String filename = rs.getString("FILENAME");
       long modified = rs.getTimestamp("MODIFIED").getTime();
       File file = new File(filename);
       if (file.exists() && file.lastModified() == modified) {
         list.add(file);
       }
     }
   } catch (SQLException se) {
     LOGGER.error(null, se);
     return null;
   } finally {
     close(rs);
     close(ps);
     close(conn);
   }
   return list;
 }
예제 #4
0
  public ValoresAtualizaJob retornaNovosValores(Connection conn, JobLote job) throws SQLException {

    PreparedStatement stmt = null;
    ResultSet rs = null;
    ValoresAtualizaJob obj = null;

    String sql =
        " select sum(qtd_transf) qtd_transf, sum(qtd_sucata) qtd_sucata, sum(hr_tot) hr_tot from joblote\n"
            + " where job = ? and operacao = ? ";

    stmt = conn.prepareStatement(sql);
    stmt.setString(1, job.getJob().trim().replace(".", ""));
    stmt.setInt(2, job.getOperNum());
    rs = stmt.executeQuery();

    if (rs.next()) {

      obj = new ValoresAtualizaJob();
      obj.setQtdTransf(rs.getDouble("qtd_transf"));
      obj.setQtdSucata(rs.getDouble("qtd_sucata"));
      obj.setHoraTotal(rs.getDouble("hr_tot"));
    }

    return obj;
  }
예제 #5
0
파일: Main.java 프로젝트: 8CAKE/ALE
  public boolean validLogin(String username, String password) {
    boolean validUser = false;
    try {

      dbStm =
          dbCon.prepareStatement(
              "SELECT * FROM userInfo WHERE username = "******"\"" + username + "\"" + ";");

      dbRs = dbStm.executeQuery();

      while (dbRs.next()) {
        String un = "";
        String pw = "";

        un = dbRs.getString("username");
        System.out.println(un + " " + username);
        pw = dbRs.getString("password");
        System.out.println(pw + " " + password);

        if (((username.equals(un) == true) && ((password.equals(pw) == true)))) {
          validUser = true;
          System.out.println("Valid User");
        }
      }

    } catch (Exception e) {
      e.printStackTrace();
    }

    return validUser;
  }
예제 #6
0
 public Insert(java.awt.Frame parent, boolean modal, Connection cn, String h) {
   super(parent, modal);
   initComponents();
   con = cn;
   jPanel1.setBounds(0, 0, 800, 1000);
   s = h;
   try {
     Statement st = con.createStatement();
     ResultSet rs1 = st.executeQuery("select * from " + s);
     ResultSetMetaData rd = rs1.getMetaData();
     count = rd.getColumnCount();
     if (count >= 5) jPanel1.setLayout(new java.awt.GridLayout(count, 5, 20, 20));
     else jPanel1.setLayout(new java.awt.GridLayout(count, 5, 40, 40));
     l = new JLabel[count];
     l2 = new JLabel[count];
     l1 = new JLabel[count];
     t = new JTextField[count];
     jLabel1.setText("INSERT INTO " + s);
     getContentPane().add(jLabel1, BorderLayout.NORTH);
     for (i = 1; i <= count; i++) {
       if (rd.isNullable(i) == ResultSetMetaData.columnNoNulls) l2[i - 1] = new JLabel("Not Null");
       else l2[i - 1] = new JLabel("Nullable");
       l[i - 1] = new JLabel(rd.getColumnName(i));
       jPanel1.add(l[i - 1]);
       l1[i - 1] = new JLabel("(" + rd.getColumnTypeName(i) + ")");
       jPanel1.add(l1[i - 1]);
       jPanel1.add(l2[i - 1]);
       t[i - 1] = new JTextField();
       jPanel1.add(t[i - 1]);
     }
   } catch (Exception e) {
     System.out.println(e);
   }
 }
예제 #7
0
  private void jTbdescripcionKeyPressed(
      java.awt.event.KeyEvent evt) { // GEN-FIRST:event_jTbdescripcionKeyPressed

    try {
      // se comienza la conexion con la base de datos
      try {
        con = new Conexion();

      } catch (ClassNotFoundException ex) {
        Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
      } catch (SQLException ex) {
        Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
      } catch (InstantiationException ex) {
        Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
      } catch (IllegalAccessException ex) {
        Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
      }

      String nom = jTbdescripcion.getText();
      String sql = "SELECT * FROM productos WHERE nombre_producto LIKE '" + nom + "%'";
      rs = con.Consulta(sql);

      if (rs == null)
        JOptionPane.showMessageDialog(
            null, "No se encontro: " + jTbdescripcion.getText() + " en la base de datos.");

      // Para establecer el modelo al JTable

      DefaultTableModel buscar =
          new DefaultTableModel() {
            @Override
            public boolean isCellEditable(int rowIndex, int vColIndex) {
              return false;
            }
          };
      this.jTbuscar.setModel(buscar);

      // Obteniendo la informacion de las columnas que estan siendo consultadas
      ResultSetMetaData rsMd = rs.getMetaData();
      // La cantidad de columnas que tiene la consulta
      int cantidadColumnas = rsMd.getColumnCount();
      // Establecer como cabezeras el nombre de las colimnas
      for (int i = 1; i <= cantidadColumnas; i++) {
        buscar.addColumn(rsMd.getColumnLabel(i));
      }

      while (rs.next()) {
        Object[] fila = new Object[cantidadColumnas];

        for (int i = 0; i < cantidadColumnas; i++) {

          fila[i] = rs.getObject(i + 1);
        }
        buscar.addRow(fila);
      }

    } catch (SQLException ex) {
      Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
    }
  } // GEN-LAST:event_jTbdescripcionKeyPressed
예제 #8
0
 public void actionPerformed(ActionEvent evt) {
   // 删除原来的JTable(JTable使用scrollPane来包装)
   if (scrollPane != null) {
     jf.remove(scrollPane);
   }
   try (
   // 根据用户输入的SQL执行查询
   ResultSet rs = stmt.executeQuery(sqlField.getText())) {
     // 取出ResultSet的MetaData
     ResultSetMetaData rsmd = rs.getMetaData();
     Vector<String> columnNames = new Vector<>();
     Vector<Vector<String>> data = new Vector<>();
     // 把ResultSet的所有列名添加到Vector里
     for (int i = 0; i < rsmd.getColumnCount(); i++) {
       columnNames.add(rsmd.getColumnName(i + 1));
     }
     // 把ResultSet的所有记录添加到Vector里
     while (rs.next()) {
       Vector<String> v = new Vector<>();
       for (int i = 0; i < rsmd.getColumnCount(); i++) {
         v.add(rs.getString(i + 1));
       }
       data.add(v);
     }
     // 创建新的JTable
     JTable table = new JTable(data, columnNames);
     scrollPane = new JScrollPane(table);
     // 添加新的Table
     jf.add(scrollPane);
     // 更新主窗口
     jf.validate();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
예제 #9
0
  public void actionPerformed(ActionEvent ae) {
    if (ae.getSource() == b1) {
      try {
        Class.forName("oracle.jdbc.driver.OracleDriver");
        Connection con =
            DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "123");
        PreparedStatement ps =
            con.prepareStatement("select * from LoginForm where username=? and password=?");
        String UserName = t1.getText();
        String Password = jp1.getText();
        ps.setString(1, UserName);
        ps.setString(2, Password);
        ResultSet rs = ps.executeQuery();
        boolean flag = rs.next();
        if (flag) {
          new Main();
          f.setVisible(false);
        } else {
          JOptionPane.showMessageDialog(null, "Please Enter valid Name And Password");
        }

      } catch (Exception e) {
        System.out.println("Error:" + e);
      }
    } else if (ae.getSource() == b2) {
      t1.setText("");
      jp1.setText("");
    } else if (ae.getSource() == b3) {

      f.setVisible(false);
    }
  }
 public ArrayList<String> getStrings(String sql) {
   ArrayList<String> list = new ArrayList<String>();
   Connection conn = null;
   ResultSet rs = null;
   PreparedStatement ps = null;
   try {
     conn = getConnection();
     ps = conn.prepareStatement(sql);
     rs = ps.executeQuery();
     while (rs.next()) {
       String str = rs.getString(1);
       if (isBlank(str)) {
         if (!list.contains(NONAME)) {
           list.add(NONAME);
         }
       } else if (!list.contains(str)) {
         list.add(str);
       }
     }
   } catch (SQLException se) {
     LOGGER.error(null, se);
     return null;
   } finally {
     close(rs);
     close(ps);
     close(conn);
   }
   return list;
 }
예제 #11
0
  public void setQuery(String q) {
    cache = new Vector();
    try {
      ResultSet rs = statement.executeQuery(q);
      ResultSetMetaData meta = rs.getMetaData();
      colCount = meta.getColumnCount();
      headers = new String[colCount];
      for (int h = 1; h <= colCount; h++) {
        headers[h - 1] = meta.getColumnName(h);
      }
      while (rs.next()) {
        String[] record = new String[colCount];
        for (int i = 0; i < colCount; i++) {
          record[i] = rs.getString(i + 1);
        }
        cache.addElement(record);
      } // while sonu

      fireTableChanged(null);
    } // try sonu
    catch (Exception e) {
      cache = new Vector();
      e.printStackTrace();
    }
  } // setQuery sonu
예제 #12
0
  private void jButton3ActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_jButton3ActionPerformed
    try {
      Connection con =
          (Connection)
              DriverManager.getConnection("jdbc:mysql://localhost:3306/bharatmotors", "root", "");
      Statement stmt = con.createStatement();

      ResultSet resultSet = stmt.executeQuery("select Bill_No from bill;");

      String productCode = null;

      while (resultSet.next()) {
        productCode = resultSet.getString("Bill_No");
      }
      int pc = Integer.parseInt(productCode);
      System.out.println(pc);
      no.setText((String.valueOf(++pc)));
      // TODO add your handling code here:

      String part = partno.getText();
      String itemname = name.getText();
      String qty1 = qty.getText();
      String rate1 = rate.getText();
      // String amo=amount.getText();
      String noo = no.getText();
      no1 = Integer.parseInt(noo);
      cname = custname.getText();
      bill1 = bill.getText();
      addr1 = addr.getText();

      String ta = tax.getText();
      int a = Integer.parseInt(qty1);
      int b = Integer.parseInt(rate1);
      int c = a * b;
      String str = Integer.toString(c);
      amount.setText(str);
      String str1 = amount.getText();
      /* String sql1="select Quantity from lubricants";
      String sql2="UPDATE LUBRICANTS SET QUANTITY=QUANTITY-qty1 WHERE PART_NO='"+partno+"'";
      Statement stmt1=con.createStatement();
      ResultSet rs1= stmt1.executeQuery(sql1);

      String ch=rs1.getString("QUANTITY");
      int q=Integer.parseInt(qty1);
      int r=Integer.parseInt(ch);
      if(q >r)
      {
          JOptionPane.showMessageDialog(this,"STOCK UNAVAILABLE");
      }
      else
      {
          stmt1.executeUpdate(sql2);
      }*/
    } catch (SQLException ex) {
      Logger.getLogger(Billspare.class.getName()).log(Level.SEVERE, null, ex);
    }
  } // GEN-LAST:event_jButton3ActionPerformed
예제 #13
0
 private void passwordTextBoxKeyPressed(
     java.awt.event.KeyEvent evt) { // GEN-FIRST:event_passwordTextBoxKeyPressed
   // TODO add your handling code here:
   int key = evt.getKeyCode();
   if (key == KeyEvent.VK_ENTER) {
     boolean verify = false;
     String user = usernameTextBox.getText();
     String passwd = passwordTextBox.getText();
     if (user.equals("") || passwd.equals("")) {
       JOptionPane.showMessageDialog(
           AdminLogin.this, "Sorry! You must enter a Username and Password to login ");
       usernameTextBox.requestFocus();
     } else {
       Connection con = getConnection();
       try {
         ResultSet rows;
         Statement s =
             con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
         String select = "Select * from admin;";
         rows = s.executeQuery(select);
         while (rows.next()) {
           String username = rows.getString("Username");
           String password = rows.getString("Password");
           if (user.equals(username) && passwd.equals(password)) {
             verify = true;
             this.dispose();
             //                       btn.btnEnabled();
             break;
           }
         }
         if (verify == false) {
           verify = false;
           JOptionPane.showMessageDialog(
               AdminLogin.this, "Access Denied! Invalid Username or Password");
           usernameTextBox.setText("");
           passwordTextBox.setText("");
           usernameTextBox.requestFocus();
         }
       } catch (SQLException e) {
         System.out.println(e.getMessage());
       }
       if (verify == false) {
         JOptionPane.showMessageDialog(
             AdminLogin.this, "Access Denied!  Invalid Username or Password");
         usernameTextBox.setText("");
         passwordTextBox.setText("");
         usernameTextBox.requestFocus();
       } // TODO add your handling code here:
     }
   }
   if (key == KeyEvent.VK_UP) {
     usernameTextBox.grabFocus();
   }
   if (key == KeyEvent.VK_KP_UP) {
     usernameTextBox.grabFocus();
   }
 } // GEN-LAST:event_passwordTextBoxKeyPressed
  private void fullAssociated() {

    boolean associated = true;

    String SQL =
        "Select * "
            + "from XX_VMR_REFERENCEMATRIX "
            + "where M_product IS NULL AND XX_VMR_PO_LINEREFPROV_ID="
            + LineRefProv.get_ID();

    try {
      PreparedStatement pstmt = DB.prepareStatement(SQL, null);
      ResultSet rs = pstmt.executeQuery();

      while (rs.next()) {
        associated = false;
      }

      rs.close();
      pstmt.close();

    } catch (Exception a) {
      log.log(Level.SEVERE, SQL, a);
    }

    if (associated == true) {
      String SQL10 =
          "UPDATE XX_VMR_PO_LineRefProv "
              + " SET XX_ReferenceIsAssociated='Y'"
              + " WHERE XX_VMR_PO_LineRefProv_ID="
              + LineRefProv.getXX_VMR_PO_LineRefProv_ID();

      DB.executeUpdate(null, SQL10);

      //			LineRefProv.setXX_ReferenceIsAssociated(true);
      //			LineRefProv.save();

      int dialog = Env.getCtx().getContextAsInt("#Dialog_Associate_Aux");

      if (dialog == 1) {
        ADialog.info(m_WindowNo, m_frame, "MustRefresh");
        Env.getCtx().remove("#Dialog_Associate_Aux");
      }

    } else {
      String SQL10 =
          "UPDATE XX_VMR_PO_LineRefProv "
              + " SET XX_ReferenceIsAssociated='N'"
              + " WHERE XX_VMR_PO_LineRefProv_ID="
              + LineRefProv.getXX_VMR_PO_LineRefProv_ID();

      DB.executeUpdate(null, SQL10);
      //			LineRefProv.setXX_ReferenceIsAssociated(false);
      //			LineRefProv.save();
    }
  }
예제 #15
0
 public void run() {
   m_nTrans = 0;
   m_nTrans1Sec = 0;
   m_nTrans2Sec = 0;
   m_nTimeSum = 0;
   if (m_nNumRuns <= 0) return;
   Statement stmt = null;
   try {
     stmt = m_conn.createStatement();
     ResultSet set;
     // get branch count
     log("select max(branch) from " + m_Driver.getBranchName() + "\n", 2);
     set = stmt.executeQuery("select max(branch) from " + m_Driver.getBranchName());
     if (set != null && set.next()) {
       m_nMaxBranch = set.getInt(1);
       set.close();
     }
     // get teller count
     log("select max(teller) from " + m_Driver.getTellerName() + "\n", 2);
     set = stmt.executeQuery("select max(teller) from " + m_Driver.getTellerName());
     if (set != null && set.next()) {
       m_nMaxTeller = set.getInt(1);
       set.close();
     }
     // get account count
     log("select max(account) from " + m_Driver.getAccountName() + "\n", 2);
     set = stmt.executeQuery("select max(account) from " + m_Driver.getAccountName());
     if (set != null && set.next()) {
       m_nMaxAccount = set.getInt(1);
       set.close();
     }
   } catch (SQLException e) {
     log("Error getting table limits : " + e.getMessage() + "\n", 0);
   } finally {
     if (stmt != null)
       try {
         stmt.close();
       } catch (SQLException e) {
       }
     stmt = null;
   }
   //		System.out.println("Thread : " + getName() + " Branch :" + m_nMaxBranch + " Teller : " +
   // m_nMaxTeller + " Account : " + m_nMaxAccount);
   if (m_bRunText) runTextTest();
   if (m_bRunPrepared) runPrepareTest();
   if (m_bRunSProc) runProcTest();
   if (m_bCloseConnection) {
     try {
       m_conn.close();
       log("Thread connection closed", 2);
     } catch (SQLException e) {
     }
   }
   if (m_log != null) m_log.taskDone();
 }
    public void actionPerformed(ActionEvent ae) {
      try {

        Integer num = Integer.parseInt(tfdid.getText());
        String name;
        String addr;
        String contact;
        String spec;
        String workf;
        String workt;

        Statement st = cn.createStatement();
        ResultSet rs = st.executeQuery("SELECT * FROM DOC WHERE did=" + num);

        if (rs.next()) {
          num = rs.getInt("did");
          name = rs.getString("name");
          addr = rs.getString("address");
          contact = rs.getString("contact");
          spec = rs.getString("specialization");
          workf = rs.getString("workfrom");
          workt = rs.getString("workto");

          tfname.setText(name);
          taadd.setText(addr);
          tftel.setText(contact);
          taspecial.setText(spec);
          tfworkf.setText(workf);
          tfworkt.setText(workt);
        }

      } catch (SQLException sq) {
        System.out.println(sq);
      }
    }
예제 #17
0
  /**
   * metoda pobierajaca wszystkie rekordy z BD1.
   *
   * @return
   */
  public ArrayList<StudentFirst> getAllStudentFromDBfirst() {
    logger.info("getAllContactFromDB");
    ResultSet result = null;
    ArrayList<StudentFirst> students = new ArrayList<>();
    try {
      prepStmt = conn.prepareStatement("SELECT * FROM student1");
      result = prepStmt.executeQuery();
      int id, index;
      String name, surname, university, faculty, field;

      for (int i = 0; result.next(); i++) {
        id = result.getInt("stud1_id");
        index = result.getInt("stud1_index");
        name = result.getString("stud1_name");
        surname = result.getString("stud1_lastname");
        university = result.getString("stud1_university");
        faculty = result.getString("stud1_faculty");
        field = result.getString("stud1_field");
        students.add(new StudentFirst(id, index, name, surname, university, faculty, field));
        logger.info(students.get(i).toString());
      }

      if (students.size() == 0) {
        logger.info("Pusta BD?");
      }
      return students;
    } catch (SQLException e1) {
      JOptionPane.showMessageDialog(null, e1);
      e1.printStackTrace();
      return null;
    }
  }
예제 #18
0
 public boolean isValidUser() throws SQLException {
   CreateJDBCConnection jdbc = new CreateJDBCConnection();
   Statement stmt = jdbc.getStatement();
   stmt.execute("use jana;");
   String sqlQuery =
       "select password from user_details where idno = '" + nameText.getText() + "';";
   ResultSet rs = stmt.executeQuery(sqlQuery);
   while (rs.next()) {
     if (rs.getString("password").equals(passText.getText())) return true;
   }
   return false;
 }
예제 #19
0
  public long cacuAddr(String flightNum) {
    long remark = 0;
    try {
      String sqlString = "select remark from flight where flight='" + flightNum + "'";
      ResultSet rs = sqlConnection.executeQuery(sqlString);

      while (rs.next()) remark = rs.getInt(1);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return (remark - 1) * 4;
  }
예제 #20
0
  public JobProtheus retornaJob(Connection conn, JobLote lote) throws SQLException {

    ResultSet rs = null;
    PreparedStatement stmt = null;
    JobProtheus job = null;

    String sql = "select job , B1_DESC,  operacao , produto,  ";
    sql += " dt_release, job_start_date , qtd_release, setor, qtd_transf ";
    sql += " from job left join  " + DB_PROTHEUS.trim() + ".dbo.SB1000 SB1 ";
    sql += " on(produto collate SQL_Latin1_General_CP1_CI_AS = B1_COD) ";
    sql += " where job = ? and operacao = ? and SB1.D_E_L_E_T_ = '' ";
    sql += " order by dt_release, produto ";

    stmt = conn.prepareStatement(sql);
    stmt.setString(1, lote.getJob().trim());
    stmt.setInt(2, lote.getOperNum());
    rs = stmt.executeQuery();

    while (rs.next()) {

      String nJob = rs.getString("job");
      int operacao = rs.getInt("operacao");
      String produto = rs.getString("produto");
      Date dataEmissao = rs.getDate("dt_release");
      Date dataPrevisaoInicio = rs.getDate("job_start_date");
      String descricaoProduto = rs.getString("B1_DESC");
      double quantidade = rs.getDouble("qtd_release");
      String wc = rs.getString("setor");

      String emissao = dataEmissao != null ? getDateToString(dataEmissao) : "";
      String previsaoInicio = dataPrevisaoInicio != null ? getDateToString(dataPrevisaoInicio) : "";

      job = new JobProtheus();

      job.setStatus("");
      job.setJob(nJob);
      job.setOperacao(operacao);
      job.setProduto(produto.trim());
      job.setDataEmissao(emissao);
      job.setQuantidadeLiberada(quantidade);
      job.setDescricaoProduto(descricaoProduto);
      job.setCentroTrabalho(wc);

      double qtdTotal = retornaQtdTotal(conn, job); // calcula o total transferido para o job
      job.setQuantidadeCompleta(qtdTotal);
      job.setDataPrivisaoInicio(previsaoInicio);
      job.setQuantidadeFaltando(quantidade - qtdTotal); // seta o valor qtd faltando
    }

    return job; // retorna lista de jobs
  }
예제 #21
0
  public void connectUsers(String query)
        // PRE:  query must be initialized
        // POST: Updates the list of Users 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; // Number of items 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();
      }
      usersArray = new User[rowcount];
      i = 0;
      while (results.next()) // Itterate through the results set
      {
        usersArray[i] =
            new User(
                results.getInt("user_id"),
                results.getString("user_name"),
                results.getInt("balance")); // Create new User
        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 connectUsers");
    }
  }
예제 #22
0
  public void actionPerformed(java.awt.event.ActionEvent evt) {
    String sql1 =
        "select a.* FROM ANTENA a WHERE a.ID_antena='"
            + (newJPanel.jList1.getSelectedIndex() + 1)
            + "' ";
    String pom = "";
    System.out.println(sql1);
    try {
      Class.forName("oracle.jdbc.driver.OracleDriver");
      Connection conn;
      try {
        conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", user, password);

        Statement stmt1 = conn.createStatement();
        ResultSet rs1 = stmt1.executeQuery(sql1);
        while (rs1.next()) {
          NewJPanel.jTextField1.setText(rs1.getString("ID_antena"));
          NewJPanel.jTextField2.setText(rs1.getString("Producent"));
          NewJPanel.jTextField3.setText(rs1.getString("Numer_identyfikacyjny"));
          NewJPanel.jTextField4.setText(rs1.getString("Czestotliwosc"));
          NewJPanel.jTextField5.setText(rs1.getString("Polaryzacja"));
          NewJPanel.jTextField6.setText(rs1.getString("Moc"));
          NewJPanel.jTextField7.setText(rs1.getString("Rodzaj"));
        }
      } catch (SQLException e1) {
        System.out.println("tutaj 1");
        e1.printStackTrace();
      }
    } catch (ClassNotFoundException e1) {
      System.out.println("tutaj 2");
      e1.printStackTrace();
    }
  }
예제 #23
0
  private void setamount() {

    try {
      ResultSet rst =
          DBConnection.getDBConnection()
              .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE)
              .executeQuery(
                  "SELECT Amount FROM BOOKING  where Pass_No='" + combo1.getSelectedItem() + "'");
      while (rst.next()) {
        combo8.addItem(rst.getString(1));
      }
    } catch (Exception n) {
      n.printStackTrace();
    }
  }
예제 #24
0
  private void setCombo() {

    try {
      ResultSet rst =
          DBConnection.getDBConnection()
              .createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE)
              .executeQuery(
                  "SELECT Emp.empNo, Emp.Sname, Emp.Fname, Emp.Lname, Emp.Designation FROM Emp WHERE Emp.Designation='Booking Clerk'");
      while (rst.next()) {
        combo3.addItem(rst.getString(3));
      }
    } catch (Exception n) {
      n.printStackTrace();
    }
  }
예제 #25
0
  public boolean dbOpenList(Connection connection, String sql) {
    dbClearList();
    this.oldSql = sql;
    this.oldConnection = connection;
    // apre il resultset da abbinare
    ResultSet resu = null;
    ResultSetMetaData meta;
    try {
      stat = connection.createStatement();
      resu = stat.executeQuery(sql);
      meta = resu.getMetaData();

      if (meta.getColumnCount() > 1) {
        this.contieneChiavi = true;
      }

      // righe
      while (resu.next()) {
        for (int i = 1; i <= meta.getColumnCount(); ++i) {
          if (i == 1) {
            dbItems.add((Object) resu.getString(i));
            lm.addElement((Object) resu.getString(i));
          } else if (i == 2) {
            dbItemsK.add((Object) resu.getString(i));

            // debug
            // System.out.println("list:" + String.valueOf(i) + ":" + resu.getString(i));
          } else if (i == 3) {
            dbItemsK2.add((Object) resu.getString(i));
          }
        }
      }
      this.setModel(lm);

      // vado al primo
      if (dbTextAbbinato != null) {
        // debug
        // javax.swing.JOptionPane.showMessageDialog(null,this.getKey(0).toString());
        dbTextAbbinato.setText(this.getKey(0).toString());
      }

      return (true);
    } catch (Exception e) {
      javax.swing.JOptionPane.showMessageDialog(null, e.toString());
      e.printStackTrace();
      return (false);
    } finally {
      try {
        stat.close();
      } catch (Exception e) {
      }
      try {
        resu.close();
      } catch (Exception e) {
      }
      meta = null;
    }
  }
예제 #26
0
  private void LoginButtonActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_LoginButtonActionPerformed
    // TODO add your handling code here:
    String sql = "select * from bruker where brukerNavn=? and brukerPassord=?";

    try {
      int userType = accountType.getSelectedIndex();

      pst = conn.prepareStatement(sql);
      pst.setString(1, UsrInput.getText());
      pst.setString(2, PswdInput.getText());
      rs = pst.executeQuery();

      if (rs.next()) {
        // JOptionPane.showMessageDialog(null,"Username and password is correct");
        close();
        if (userType == 0) {
          MainPage m = new MainPage();
          m.setVisible(true);
        } else {
          fMainPage fm = new fMainPage();
          fm.setVisible(true);
        }

      } else {
        JOptionPane.showMessageDialog(null, "Username or password is incorrect");
      }
    } catch (Exception e) {
      JOptionPane.showMessageDialog(null, e);
    }
  } // GEN-LAST:event_LoginButtonActionPerformed
 private Double toDouble(ResultSet rs, String column) throws SQLException {
   Object obj = rs.getObject(column);
   if (obj instanceof Double) {
     return (Double) obj;
   }
   return null;
 }
예제 #28
0
  public boolean verificaSeSetorTemLinhaTempo(Connection conn, String setor) throws SQLException {

    PreparedStatement stmt = null;
    ResultSet rs = null;
    String sql = "select linha_tempo from setor where setor = ? and linha_tempo = ? ";

    stmt = conn.prepareStatement(sql);
    stmt.setString(1, setor.trim());
    stmt.setBoolean(2, true);
    rs = stmt.executeQuery();

    if (rs.next()) {
      return true;
    } else {
      return false;
    }
  }
예제 #29
0
 public void setJenis() {
   dataJenis = new ArrayList<Jenis>();
   try {
     String qry = "SELECT * from jenis";
     ResultSet rs = stm.executeQuery(qry);
     while (rs.next()) {
       Jenis j = new Jenis();
       j.setIdJenis(rs.getInt("id_jenis"));
       j.setNamaJenis(rs.getString("nama_jenis"));
       dataJenis.add(j);
     }
   } catch (SQLException SQLerr) {
     SQLerr.printStackTrace();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
예제 #30
0
  public int dingPiao(String flightNum, String day, int seats) {
    int leftSeats = 0;
    try {
      long index = cacuIndex(day);
      long address = cacuAddr(flightNum);
      long absoluteAddress = index + address;

      raf.seek(absoluteAddress);
      int bookedSeats = raf.readInt();

      String sqlString = "select seat,week from flight where flight='" + flightNum + "' ";
      ResultSet rs = sqlConnection.executeQuery(sqlString);

      int totalSeats = 0;
      String week = "";
      while (rs.next()) {
        totalSeats = rs.getInt(1);
        week = rs.getString(2);
      }

      String c = isAbsence(day);
      int flag = 0;
      for (int i = 0; i < week.length(); i++) {
        String w = week.substring(i, i + 1);
        if (c.equals(w)) {
          flag = 1;
          break;
        }
      }

      if (flag == 1) {
        leftSeats = totalSeats - bookedSeats;

        if (leftSeats >= seats) {
          raf.seek(absoluteAddress);
          raf.writeInt(bookedSeats + seats);
          return -1;
        } else return leftSeats;
      } else return -2;

    } catch (Exception e) {
      e.printStackTrace();
    }

    return leftSeats;
  }