Example #1
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();
    }
  }
 public synchronized void updateThumbnail(
     String name, long modified, int type, DLNAMediaInfo media) {
   Connection conn = null;
   PreparedStatement ps = null;
   try {
     conn = getConnection();
     ps = conn.prepareStatement("UPDATE FILES SET THUMB = ? WHERE FILENAME = ? AND MODIFIED = ?");
     ps.setString(2, name);
     ps.setTimestamp(3, new Timestamp(modified));
     if (media != null) {
       ps.setBytes(1, media.getThumb());
     } else {
       ps.setNull(1, Types.BINARY);
     }
     ps.executeUpdate();
   } catch (SQLException se) {
     if (se.getErrorCode() == 23001) {
       LOGGER.debug(
           "Duplicate key while inserting this entry: "
               + name
               + " into the database: "
               + se.getMessage());
     } else {
       LOGGER.error(null, se);
     }
   } finally {
     close(ps);
     close(conn);
   }
 }
 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;
 }
 public void excluir(Oriundo oriundo) throws SQLException {
   Connection con =
       DriverManager.getConnection(
           new conexao().url,
           new conexao().config.getString("usuario"),
           new conexao().config.getString("senha"));
   PreparedStatement ps = null;
   String sqlExcluir = "DELETE FROM oriundo WHERE codigo=?";
   try {
     ps = con.prepareStatement(sqlExcluir);
     ps.setInt(1, oriundo.getCodigo());
     ps.executeUpdate();
     JOptionPane.showMessageDialog(
         null, "Ecluido Com Sucesso: ", "Mensagem do Sistema - Excluir", 1);
   } catch (NumberFormatException e) {
     JOptionPane.showMessageDialog(
         null, "NumberFormaterExeption Erro: " + e.getMessage(), "ClasseDAO Func.Excluir", 0);
     e.printStackTrace();
   } catch (NullPointerException e) {
     JOptionPane.showMessageDialog(
         null, "NullPointerException Erro: " + e.getMessage(), "ClasseDAO Func. Excluir", 0);
     e.printStackTrace();
   } catch (SQLException e) {
     JOptionPane.showMessageDialog(
         null, "SQLException Erro: " + e.getMessage(), "ClasseDAO Func. Excluir", 0);
     e.printStackTrace();
   } catch (Exception e) {
     JOptionPane.showMessageDialog(
         null, "Exception Erro: " + e.getMessage(), "ClasseDAO Func. Excluir", 0);
     e.printStackTrace();
   } finally {
     ps.close();
     con.close();
   }
 }
 private void ListValueChanged(
     javax.swing.event.ListSelectionEvent evt) { // GEN-FIRST:event_ListValueChanged
   // TODO add your handling code here:
   // String part=partno.getText();
   try {
     String sql =
         "SELECT  TYPE,ITEM_NAME,QUANTITY,MRP FROM MOTORS WHERE ITEM_NAME='"
             + List.getSelectedValue()
             + "'";
     Class.forName("com.mysql.jdbc.Driver");
     Connection con =
         (Connection)
             DriverManager.getConnection("jdbc:mysql://localhost:3306/bharatmotors", "root", "");
     Statement stmt = con.createStatement();
     ResultSet rs = stmt.executeQuery(sql);
     while (rs.next()) {
       partno.setText(rs.getString("TYPE"));
       name.setText(rs.getString("ITEM_NAME"));
       qty.setText(rs.getString("QUANTITY"));
       rate.setText(rs.getString("MRP"));
     }
   } catch (Exception e) {
     JOptionPane.showMessageDialog(null, e.toString());
   }
 } // GEN-LAST:event_ListValueChanged
Example #6
0
    public void actionPerformed(ActionEvent e) {
      try {
        String name = JOptionPane.showInputDialog("Enter the UserId:");
        String name1 = JOptionPane.showInputDialog("Enter the Password:"******"Enter the MobileNo:");
        // int name2=Integer.parseInt(name22);
        String name3 = JOptionPane.showInputDialog("Enter the DOB(dd/mm/yyyy):");
        DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
        Connection con =
            DriverManager.getConnection(
                "jdbc:oracle:thin:@localhost:1521:xe", "system", "9696030257");
        Statement st = con.createStatement();
        st.executeUpdate(
            "insert into database values('"
                + name
                + "','"
                + name1
                + "','"
                + name2
                + "','"
                + name3
                + "')");
        st.executeUpdate("commit");
        JOptionPane.showMessageDialog(
            null,
            "Hi !! Welcome in Our Database.Your userId is  < "
                + name
                + " > And Password is < ******* >");

      } catch (Exception ex) {
        System.out.print(ex);
        JOptionPane.showMessageDialog(null, "Please Fill All Entry OR choose another UsetId.");
      }
    }
  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);
    }
  }
Example #8
0
  private void isEdit(Boolean isEdit) {
    if (isEdit) {
      try {
        Connection con = FrameLogin.getConnect();
        String sql = "SELECT * FROM Persons WHERE personId = " + Id;
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
        if (rs.first()) {
          String firstname = rs.getString("FirstName");
          String lastname = rs.getString("LastName");
          String cellphone = rs.getString("CellPhoneNo");
          String homephone = rs.getString("HomePhoneNo");
          String gradyear = rs.getString("Graduation Year");
          String Gender = rs.getString("Gender");

          firstName.setText(firstname);
          lastName.setText(lastname);
          cellPhone.setText(cellphone);
          homePhone.setText(homephone);
          gradYear.setText(gradyear);
          gender.setSelectedItem(Gender);
          jLabel7.setVisible(false);
          studentId.setVisible(false);

        } else {
          MessageBox.infoBox("Error: ID not found", "Error");
        }
      } catch (Exception e) {
        MessageBox.infoBox(e.toString(), "Error in isEdit");
      }
    }
    FrameLogin.closeConnect();
  }
 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;
 }
  public void connectItems(String query)
        // PRE:  query must be initialized
        // POST: Updates the list of Items based on the query.
      {
    String driver = "org.apache.derby.jdbc.ClientDriver"; // Driver for DB
    String url = "jdbc:derby://localhost:1527/ShopDataBase"; // Url for DB
    String user = "******"; // Username for db
    String pass = "******"; // Password for db
    Connection myConnection; // Connection obj to db
    Statement stmt; // Statement to execute a result appon
    ResultSet results; // A set containing the returned results
    int rowcount; // Num objects in the resultSet
    int i; // Index for the array

    try { // Try connection to db

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

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

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

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

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

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

    } catch (Exception e) // Cannot connect to db
    {
      System.err.println(e.toString());
      System.err.println("Error, something went horribly wrong in connectItems!");
    }
  }
  private void 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
Example #12
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
Example #13
0
 private void submitButtonActionPerformed(
     java.awt.event.ActionEvent evt) { // GEN-FIRST:event_submitButtonActionPerformed
   // TODO add your handling code here:
   Connection con = FrameLogin.getConnect();
   String SQLInsert =
       "INSERT INTO `2761DB`.`Persons` (`FirstName`, `LastName`, `CellPhoneNo`, `HomePhoneNo`, "
           + "`SchoolId`, `Graduation Year`, `Gender`) VALUES ('"
           + firstName.getText()
           + "', '"
           + lastName.getText()
           + "', '"
           + cellPhone.getText()
           + "', '"
           + homePhone.getText()
           + "', '"
           + studentId.getText()
           + "', '"
           + gradYear.getText()
           + "', '"
           + (String) (gender.getSelectedItem())
           + "');";
   String SQLUpdate =
       "UPDATE `2761DB`.`Persons` SET `FirstName` = '"
           + firstName.getText()
           + "', `LastName` = '"
           + lastName.getText()
           + "', `CellPhoneNo` = ' "
           + cellPhone.getText()
           + "', `HomePhoneNo` = '"
           + homePhone.getText()
           + "', `Graduation Year` = '"
           + gradYear.getText()
           + "', `Gender` = '"
           + (String) (gender.getSelectedItem())
           + "' WHERE `PersonId` = '"
           + Id
           + "';";
   // UPDATE `2761DB`.`Persons` SET `FirstName`='Robbie', `LastName`='Tacescu', `CellPhoneNo`='',
   // `HomePhoneNo`='559300', `SchoolId`='15648916', `Graduation Year`='6545', `Gender`='males'
   // WHERE
   // `PersonId`='42';
   try {
     if (isEdit) {
       Statement stmt = con.createStatement();
       // System.out.println(SQLUpdate);
       stmt.executeUpdate(SQLUpdate);
     } else {
       Statement stmt = con.createStatement();
       // System.out.println(SQLInsert);
       stmt.executeUpdate(SQLInsert);
     }
   } catch (SQLException err) {
     MessageBox.infoBox(err.toString(), "Error in AddUserForm submitButton");
   }
   FrameLogin.closeConnect();
   this.dispose();
 } // GEN-LAST:event_submitButtonActionPerformed
Example #14
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();
 }
Example #15
0
 private void Update_table() {
   try {
     Connection conn = getConnect();
     String sql = "SELECT * FROM LoggedInPeople";
     PreparedStatement pst = conn.prepareStatement(sql);
     ResultSet rs = pst.executeQuery();
     PeopleLoggedIn.setModel(DbUtils.resultSetToTableModel(rs));
     closeConnect();
   } catch (Exception e) {
     System.out.println(e);
   }
 }
  public void updateTables(String updateQuery1, String updateQuery2, String updateQuery3)
        // PRE:  updateQuery1,updateQuery2, updateQuery3 must be initialized
        // POST: Updates the list of Items based on the querys.
      {
    String driver = "org.apache.derby.jdbc.ClientDriver"; // Driver for DB
    String url = "jdbc:derby://localhost:1527/ShopDataBase"; // Url for DB
    String user = "******"; // Username for db
    String pass = "******"; // Password for db
    Connection myConnection; // Connection obj to db
    Statement stmt; // Statement to execute a result appon
    ResultSet results; // A set containing the returned results
    int i; // Index for the array
    try // Try connection to db
    {

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

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

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

      stmt.executeUpdate(updateQuery2);

      stmt.executeUpdate(updateQuery3);

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

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

    } catch (Exception e) // Cannot connect to db
    {
      System.err.println(e.toString());
      System.err.println("Error, something went horribly wrong! in updateTables");
    }
  }
  public void cleanup() {
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    try {
      conn = getConnection();
      ps = conn.prepareStatement("SELECT COUNT(*) FROM FILES");
      rs = ps.executeQuery();
      dbCount = 0;

      if (rs.next()) {
        dbCount = rs.getInt(1);
      }

      rs.close();
      ps.close();
      PMS.get().getFrame().setStatusLine(Messages.getString("DLNAMediaDatabase.2") + " 0%");
      int i = 0;
      int oldpercent = 0;

      if (dbCount > 0) {
        ps =
            conn.prepareStatement(
                "SELECT FILENAME, MODIFIED, ID FROM FILES",
                ResultSet.TYPE_FORWARD_ONLY,
                ResultSet.CONCUR_UPDATABLE);
        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) {
            rs.deleteRow();
          }
          i++;
          int newpercent = i * 100 / dbCount;
          if (newpercent > oldpercent) {
            PMS.get()
                .getFrame()
                .setStatusLine(Messages.getString("DLNAMediaDatabase.2") + newpercent + "%");
            oldpercent = newpercent;
          }
        }
      }
    } catch (SQLException se) {
      LOGGER.error(null, se);
    } finally {
      close(rs);
      close(ps);
      close(conn);
    }
  }
 public void userHasLogged(String user) {
   boolean isAnonymous = "".equals(StringUtils.parseName(user));
   String title =
       "Smack Debug Window -- "
           + (isAnonymous ? "" : StringUtils.parseBareAddress(user))
           + "@"
           + connection.getServiceName()
           + ":"
           + connection.getPort();
   title += "/" + StringUtils.parseResource(user);
   frame.setTitle(title);
 }
 static {
   try {
     Class.forName("com.mysql.jdbc.Driver");
     con = DriverManager.getConnection("jdbc:mysql:///hospital", "root", "root");
     pa = con.prepareStatement("insert into patient values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ");
     pd = con.prepareStatement("delete from patient where pid=? ");
     pl = con.prepareStatement("select * from patient order by pid");
     pps = con.prepareStatement("select * from patient where pid=? ");
     pps1 = con.prepareStatement("select * from patient where plnm= ?");
   } catch (Exception e) {
     System.out.println(e);
   }
 }
  public void actionPerformed(ActionEvent e) {
    Object source = e.getSource();

    if (source == bRes) {
      tname.setText("");
      textra.setText("");
    } else {
      if (it.isSelected()) field = 1;
      else if (civil.isSelected()) field = 2;
      else if (mech.isSelected()) field = 3;

      if (tname.getText().equals("") | textra.getText().equals("") | field == 0)
        JOptionPane.showMessageDialog(null, "Please Fill in All Entries!!");
      else {
        String sal = (String) cbsal.getSelectedItem();

        try {
          // Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
          // Connection conn=DriverManager.getConnection("jdbc:odbc:go");
          Class.forName("com.mysql.jdbc.Driver").newInstance();
          Connection conn = DriverManager.getConnection("jdbc:mysql:///go", "root", "");
          Statement pst = conn.createStatement();

          pst.executeUpdate(
              "Insert into company values('"
                  + tname.getText()
                  + "','"
                  + textra.getText()
                  + "','"
                  + (String) sal
                  + "','"
                  + field
                  + "','"
                  + tusr.getText()
                  + "','"
                  + tpwd.getText()
                  + "')");
          conn.close();
          String msg =
              "Your Details are Stored. Login again to View Related applicants!  Thank You!!";
          JOptionPane.showMessageDialog(null, msg);
          setVisible(false);
          login ab = new login();

        } catch (Exception exc) {
          JOptionPane.showMessageDialog(null, tname.getText() + " : " + exc);
          System.exit(0);
        }
      }
    }
  }
  private void Update_Table() {
    try {

      String sql = "select * from Bank_001";
      PreparedStatement pst = conn.prepareStatement(sql);
      ResultSet rs = pst.executeQuery();

      table.setModel(DbUtils.resultSetToTableModel(rs));
      conn.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Example #22
0
 private void logIn(int personId) {
   Connection con = getConnect();
   try {
     // MessageBox.infoBox("You have successfully logged in", "Login");
     // INSERT INTO LogInOut (PersonId, TimeIn) VALUES (1, NOW())
     String SQLLogin = "******" + personId + ", NOW())";
     Statement stmtLogin = con.createStatement();
     stmtLogin.executeUpdate(SQLLogin);
     Update_table();
   } catch (SQLException err) {
     MessageBox.infoBox(err.toString(), "Error");
   }
   closeConnect();
 }
 public List<Oriundo> listar() throws SQLException {
   List<Oriundo> resultado = new ArrayList<Oriundo>();
   conexao propCon = new conexao();
   Connection con =
       DriverManager.getConnection(
           new conexao().url,
           propCon.config.getString("usuario"),
           propCon.config.getString("senha"));
   PreparedStatement ps = null;
   ResultSet rs = null;
   String sqlListar = "SELECT * FROM oriundo Order by codigo DESC";
   Oriundo oriundo;
   try {
     ps = con.prepareStatement(sqlListar);
     rs = ps.executeQuery();
     // if(rs==null){
     // return null;
     // }
     while (rs.next()) {
       oriundo = new Oriundo();
       oriundo.setCodigo(rs.getInt("codigo"));
       oriundo.setDescricao(rs.getString("descricao"));
       oriundo.setData_cadastro(rs.getDate("data_cadastro"));
       oriundo.setDia_fechamento(rs.getInt("dia_fechamento"));
       oriundo.setDia_pag(rs.getInt("dia_pag"));
       resultado.add(oriundo);
     }
   } catch (NumberFormatException e) {
     JOptionPane.showMessageDialog(
         null, "NumberFormaterExeption Erro: " + e.getMessage(), "ClasseDAO Func.Localizar", 0);
     e.printStackTrace();
   } catch (NullPointerException e) {
     JOptionPane.showMessageDialog(
         null, "NullPointerException Erro: " + e.getMessage(), "ClasseDAO Func. Localizar", 0);
     e.printStackTrace();
   } catch (SQLException e) {
     JOptionPane.showMessageDialog(
         null, "SQLException Erro: " + e.getMessage(), "ClasseDAO Func. Localizar", 0);
     e.printStackTrace();
   } catch (Exception e) {
     JOptionPane.showMessageDialog(
         null, "Exception Erro: " + e.getMessage(), "ClasseDAO Func. Localizar", 0);
     e.printStackTrace();
   } finally {
     ps.close();
     con.close();
   }
   return resultado;
 }
Example #24
0
  InsertData(Graphics g, int time) {

    // ***************************************************
    String response = JOptionPane.showInputDialog(null, "INPUT YOUR INTIALS.");
    String initials = response.substring(0, 3);
    Date date = new Date();

    String dateString = "" + date;

    String name = initials;
    String maze = "EASY";
    int score = time;
    try {
      String url = "jdbc:mysql://pascobulldogs.com:3306/web?user=webuser&password=w0506r";

      String sqlInsert =
          "INSERT INTO maze VALUES ('','"
              + name
              + "','"
              + maze
              + "','"
              + score
              + "','"
              + dateString
              + "');";
      g.drawString("SCORE RECORED. REFRESH TO START OVER!", 10, 380);

      // System.out.println(sqlInsert);
      //	System.out.println (url);
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      conn = DriverManager.getConnection(url);
      // cwc added this
      stmt = conn.createStatement();
      stmt.executeUpdate(sqlInsert);
      // i added this
      conn.close();
    } catch (Exception e) {
      // System.err.println ("Cannot connect to database server.");
    } finally {
      if (conn != null) {
        try {
          conn.close();
          //   System.out.println ("Database connection terminated");
        } catch (Exception e) {
          /* ignore close errors */
        }
      }
    }
  }
  public void actionPerformed(ActionEvent ae) {
    String str = ae.getActionCommand();
    if (str.equals("Ok")) {
      String str1 = (String) jcmname.getSelectedItem();

      Connection con = null;
      Statement stat = null;

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

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

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

        } catch (Exception ex) {
        }

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

    if (str.equals("can")) {
      this.dispose();
      // new menu(1);
    }
  }
Example #26
0
  public void connect() {
    try {
      try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/root", "root", "");
        statement = connection.createStatement();
        statement1 = connection.createStatement();

      } catch (Exception e) {
        e.printStackTrace();
      }
    } catch (Exception e) {
      JOptionPane.showMessageDialog(null, "JavaError:Not Connect");
    }
  }
Example #27
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;
  }
Example #28
0
  public JobIniciado retornaUltimoLote(Connection conn, String job, int operacao)
      throws SQLException {

    String sql =
        " select job, operacao, tripulacao,recurso, max(data_fim) \n"
            + "from joblote where job = ? and operacao = ? \n"
            + "group by job, operacao, tripulacao, recurso ";

    PreparedStatement stmt = null;
    ResultSet rs = null;
    JobIniciado iniciado = null;

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

    if (rs.next()) {

      iniciado = new JobIniciado();
      iniciado.setJob(rs.getString(1));
      iniciado.setOperacao(rs.getInt(2));
      iniciado.setTripulacao(rs.getDouble(3));
      iniciado.setRecurso(rs.getString(4));
      Timestamp data = rs.getTimestamp(5);
      iniciado.setData(Validacoes.getDataHoraString(data));
    }

    return iniciado;
  }
Example #29
0
  public static int retornaQtdTotal(Connection conn, JobProtheus job) throws SQLException {

    PreparedStatement stmt = null;
    ResultSet rs = null;
    int qtdTotal = 0;
    int qtdSucata = 0;

    String sqlVerQtd =
        "select job, sum(qtd_transf), sum(hr_tot), sum(qtd_sucata) from jobLote where job = ? and operacao = ? group by job";
    stmt = conn.prepareStatement(sqlVerQtd);
    stmt.setString(1, job.getJob().trim());
    stmt.setInt(2, job.getOperacao());
    rs = stmt.executeQuery();

    String qtdJob = "";
    double totHora = 0;

    while (rs.next()) {
      qtdJob = rs.getString(1); // numero job
      qtdTotal = rs.getInt(2); // quantidade total
      totHora = rs.getInt(3); // hora total em minutos
      qtdSucata = rs.getInt(4);
    }

    return qtdTotal + qtdSucata;
  }
Example #30
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;
    }
  }