Beispiel #1
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.");
      }
    }
Beispiel #2
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
  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 updateRecord() {
    String totalSeat, alotSeat, vacentSeat, strHostel;
    try {
      rs = statement.executeQuery("select hostelName from hostelStatus");
      while (rs.next()) {
        strHostel = rs.getString(1);

        try {
          rs1 = statement1.executeQuery("select count(*) from " + strHostel + "");
          rs1.next();
          totalSeat = rs1.getString(1);

          rs1 = statement1.executeQuery("select count(*) from " + strHostel + " where status='F'");
          rs1.next();
          alotSeat = rs1.getString(1);

          try {
            vacentSeat = String.valueOf(Integer.parseInt(totalSeat) - Integer.parseInt(alotSeat));
            statement1.executeUpdate(
                "update hostelStatus set totalSeat='"
                    + totalSeat
                    + "',vacentSeat='"
                    + vacentSeat
                    + "'where hostelName='"
                    + strHostel
                    + "'");
            statement1.executeUpdate("commit");
            rs1.close();
          } catch (SQLException sqle) {
            JOptionPane.showMessageDialog(null, sqle);
          }

        } catch (SQLException sqle) {
          JOptionPane.showMessageDialog(null, "Error " + sqle);
        }
      }
    } catch (SQLException sq) {
      JOptionPane.showMessageDialog(null, sq);
    }
  }
  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);
        }
      }
    }
  }
Beispiel #6
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();
 }
Beispiel #7
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 */
        }
      }
    }
  }
  private void jButton4ActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_jButton4ActionPerformed
    // TODO add your handling code here:
    String wash = chrg.getText();
    cname = custname.getText();
    addr1 = addr.getText();
    total.setText(String.valueOf(tamount));
    String a = lcharge.getText();
    String b = total.getText();
    String j = la.getText();
    String c = con.getText();
    int d = Integer.parseInt(b);
    int e = Integer.parseInt(a);
    int g = Integer.parseInt(wash);
    int h = Integer.parseInt(c);
    int i = Integer.parseInt(j);
    int f = d + e + g + h + i;
    toamnt.setText(String.valueOf(f));
    String sql =
        "insert into bill(Bill_No,Bill_Date,Cust_Name,Cust_Addr,P_Details,Amount) values('"
            + no1
            + "','"
            + bill1
            + "','"
            + cname
            + "','"
            + addr1
            + "','"
            + pd
            + "','"
            + toamnt
            + "')";

    try {
      Class.forName("com.mysql.jdbc.Driver");
      Connection con =
          (Connection)
              DriverManager.getConnection("jdbc:mysql://localhost:3306/bharatmotors", "root", "");
      Statement stmt = con.createStatement();
      stmt.executeUpdate(sql);

    } catch (Exception e2) {
      JOptionPane.showMessageDialog(this, e2.getMessage());
    }
  } // GEN-LAST:event_jButton4ActionPerformed
Beispiel #9
0
 private void logOut(int personId) {
   Connection con = getConnect();
   try {
     // MessageBox.infoBox("You have successfully logged out", "Logout");
     // UPDATE LogInOut SET TimeOut = NOW() WHERE PersonId = 1 AND TimeOut IS NULL
     String SQLLogin =
         "******"
             + personId
             + " AND TimeOut IS NULL";
     Statement stmtLogin = con.createStatement();
     stmtLogin.executeUpdate(SQLLogin);
     Update_table();
   } catch (SQLException err) {
     System.out.println(err);
     MessageBox.infoBox(err.toString(), "Error");
   }
   closeConnect();
 }
Beispiel #10
0
 public void actionPerformed(ActionEvent e) {
   String name6 = JOptionPane.showInputDialog("Enter old Password:"******"Enter New Password:"******"jdbc:oracle:thin:@localhost:1521:xe", "system", "9696030257");
     Statement st = con.createStatement();
     ResultSet rs = st.executeQuery("select * from database where password='******'");
     rs.next();
     String k8 = rs.getString("password");
     if (k8.equals(name6)) {
       st.executeUpdate(
           "update database set password='******' where password='******'");
       JOptionPane.showMessageDialog(null, "Your  Password  has  been  Reset");
       new Jf();
     }
   } catch (Exception ex) {
     System.out.print(ex);
     JOptionPane.showMessageDialog(null, "Please Enter valid DATA .");
   }
 }
 private void jButton1ActionPerformed(
     java.awt.event.ActionEvent evt) { // GEN-FIRST:event_jButton1ActionPerformed
   // TODO add your handling code here:
   String part = partno.getText();
   String itemname = name.getText();
   String qty1 = qty.getText();
   String rate1 = rate.getText();
   String no1 = no.getText();
   String cname = custname.getText();
   String bill1 = bill.getText();
   String addr1 = addr.getText();
   String ta = tax.getText();
   String str1 = amount.getText();
   DefaultTableModel model = (DefaultTableModel) Table.getModel();
   model.addRow(
       new Object[] {
         (String.valueOf(++i)),
         partno.getText(),
         name.getText(),
         tax.getText(),
         qty.getText(),
         rate.getText(),
         amount.getText()
       });
   pd = pd + "," + "(" + part + "," + itemname + "," + qty1 + ")";
   tamount = tamount + Integer.parseInt(str1);
   try {
     Connection con =
         (Connection)
             DriverManager.getConnection("jdbc:mysql://localhost:3306/bharatmotors", "root", "");
     Statement stmt2 = con.createStatement();
     stmt2.executeUpdate(
         "UPDATE MOTORS SET QUANTITY=QUANTITY-'" + qty1 + "' WHERE ITEM_NAME='" + part + "'");
   } catch (Exception e) {
     JOptionPane.showMessageDialog(null, e.toString());
   }
 } // GEN-LAST:event_jButton1ActionPerformed
Beispiel #12
0
    public void actionPerformed(ActionEvent e) {

      String name8 = JOptionPane.showInputDialog("Enter old MobileNo:");
      String name9 = JOptionPane.showInputDialog("Enter New MobileNo:");
      try {
        DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
        Connection con =
            DriverManager.getConnection(
                "jdbc:oracle:thin:@localhost:1521:xe", "system", "9696030257");
        Statement st = con.createStatement();
        ResultSet rs = st.executeQuery("select * from database where mob='" + name8 + "'");
        rs.next();
        String k9 = rs.getString("mob");
        if (k9.equals(name8)) {
          st.executeUpdate("update database set mob='" + name9 + "' where mob='" + name8 + "'");
          JOptionPane.showMessageDialog(
              null, "Your  Mobile is  Reset . Now Your mobile no is <  " + name9 + "  >");
          new Jf();
        }
      } catch (Exception ex) {
        System.out.print(ex);
        JOptionPane.showMessageDialog(null, "Please Enter valid DATA.");
      }
    }
Beispiel #13
0
 public void actionPerformed(ActionEvent e) {
   if (e.getSource() == b) {
     if (makeConnection()) {
       if (!t1.getText().equals("")
           & !t2.getText().equals("")
           & !t3.getText().equals("")
           & !t4.getText().equals("")) {
         det dez = new det();
         if (dez.date(t4.getText())) {
           String a = t1.getText();
           String b = t2.getText();
           String c = t3.getText();
           String d = t4.getText();
           String ef = t5.getText();
           try {
             st = cn.createStatement();
             String sql = "insert into detalle_ventas values('";
             sql += a;
             sql += "', '";
             sql += b + "', '" + c + "', '" + d + "', '" + ef;
             sql += "')";
             int eaz = st.executeUpdate(sql);
             javax.swing.JOptionPane.showMessageDialog(
                 null,
                 "Se han creado " + eaz + " registros en la base de datos",
                 "informacion",
                 javax.swing.JOptionPane.INFORMATION_MESSAGE);
             start();
           } catch (SQLException exz) {
             javax.swing.JOptionPane.showMessageDialog(
                 null,
                 "Ha ocurrido un error, favor de checar que la clave no ha sido ingresada ya con anterioridad  \n si el problema persiste contacte con el administrador \nError: "
                     + exz.getSQLState()
                     + ""
                     + exz.getMessage(),
                 "Error",
                 javax.swing.JOptionPane.INFORMATION_MESSAGE);
           } catch (Exception ez) {
             System.out.println(ez.getMessage());
           }
         } else {
           javax.swing.JOptionPane.showMessageDialog(
               null,
               "Favor de llenar la fecha con un formato correcto dd/mm/aaaa",
               "Error!!!",
               javax.swing.JOptionPane.ERROR_MESSAGE);
         }
       } else {
         javax.swing.JOptionPane.showMessageDialog(
             null,
             "Favor de llenar todos los datos correctamente",
             "Error!!!",
             javax.swing.JOptionPane.ERROR_MESSAGE);
       }
     } else {
       javax.swing.JOptionPane.showMessageDialog(
           null,
           "Un error ha ocurrido al intentar conectar con la base de datos, \n reinicie el componente o contacte con el administrador",
           "Error",
           javax.swing.JOptionPane.ERROR_MESSAGE);
     }
   }
   try {
     cn.close();
   } catch (Exception esa) {
     System.out.println(esa.getMessage());
   }
 }
  public void actionPerformed(ActionEvent e) {
    String a, b, c, f, g, h, j, k, l, m, n, o, p, tol = "";

    try {
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      con = DriverManager.getConnection("jdbc:odbc:db2");
      stm = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
    } catch (Exception error) {
      System.out.println(error);
    }

    if (e.getSource() == student) {
      name = "Student";
      cl.show(pnc, "cstu");
      try {
        rs = stm.executeQuery("Select * from Student");
        rs.next();
        t1.setText(rs.getString(1));
        t2.setText(rs.getString(2));
        t3.setText(rs.getString(3));
        t4.setText(rs.getString(4));
        t5.setText(rs.getString(5));
        t6.setText(rs.getString(6));
      } catch (Exception error) {
        System.out.println(error);
      }
    }

    if (e.getSource() == teacher) {
      name = "Teacher";
      cl.show(pnc, "ctea");
      try {
        rs = stm.executeQuery("Select * from Teacher");
        rs.next();
        t11.setText(rs.getString(1));
        t12.setText(rs.getString(2));
        t13.setText(rs.getString(3));
        t14.setText(rs.getString(4));
      } catch (Exception error) {
        System.out.println(error);
      }
    }

    if (e.getSource() == course) {
      name = "Course";
      cl.show(pnc, "ccou");
      try {
        rs = stm.executeQuery("Select * from Course");
        rs.next();
        t7.setText(rs.getString(1));
        t8.setText(rs.getString(2));
        t9.setText(rs.getString(3));
        t0.setText(rs.getString(4));
      } catch (Exception error) {
        System.out.println(error);
      }
    }

    if (e.getSource() == result) {
      name = "Result";
      cl.show(pnc, "cres");
      try {
        rs = stm.executeQuery("Select * from Result");
        rs.next();
        t15.setText(rs.getString(1));
        t16.setText(rs.getString(2));
        t17.setText(rs.getString(3));
        t18.setText(rs.getString(4));
        t19.setText(rs.getString(5));
        t20.setText(rs.getString(6));
        t21.setText(rs.getString(7));
        t22.setText(rs.getString(8));
        t23.setText(rs.getString(9));
        t24.setText(rs.getString(10));
        t25.setText(rs.getString(11));
        t26.setText(rs.getString(12));
        t27.setText(rs.getString(13));
      } catch (Exception error) {
        System.out.println(error);
      }
    }

    if (e.getSource() == b6) {
      Vector cols = new Vector();
      Vector rows = new Vector();

      if (z == 1) {
        String sql = "Select * from " + co;
        try {
          rs = stm.executeQuery(sql);
          meta = rs.getMetaData();
          for (int i = 1; i <= meta.getColumnCount(); i++) cols.addElement(meta.getColumnName(i));
          while (rs.next()) {
            Vector currow = new Vector();
            for (int i = 1; i <= meta.getColumnCount(); i++) currow.addElement(rs.getString(i));
            rows.addElement(currow);
          }
        } catch (Exception ex) {
          System.out.print(ex);
        }
        tb = new JTable(rows, cols);
        js = new JScrollPane(tb);
        pne2.remove(js);
        pne2.add(blk, "bb");
        cl2.show(pne2, "bb");
        pne2.add(js, "jjs");
        cl2.show(pne2, "jjs");
        pne2.remove(blk);
        z = 0;
      }
    }

    if (e.getSource() == b1) // **** ADD BUTTON ****//
    {
      if (name == "Student") {
        a = t1.getText();
        b = t2.getText();
        c = t3.getText();
        f = t4.getText();
        g = t5.getText();
        h = t6.getText();

        tol =
            "Insert into Student values ('"
                + a
                + "','"
                + b
                + "','"
                + c
                + "','"
                + f
                + "','"
                + g
                + "','"
                + h
                + "')";
      }

      if (name == "Teacher") {
        a = t11.getText();
        b = t12.getText();
        c = t13.getText();
        f = t14.getText();

        tol = "Insert into Teacher values ('" + a + "','" + b + "','" + c + "','" + f + "')";
      }

      if (name == "Course") {
        a = t7.getText();
        b = t8.getText();
        c = t9.getText();
        f = t0.getText();

        tol = "Insert into Course values ('" + a + "','" + b + "','" + c + "','" + f + "')";
      }

      if (name == "Result") {
        a = t15.getText();
        b = t16.getText();
        c = t17.getText();
        f = t18.getText();
        g = t19.getText();
        h = t20.getText();
        j = t21.getText();
        k = t22.getText();
        l = t23.getText();
        m = t24.getText();
        n = t25.getText();
        o = t26.getText();
        p = t27.getText();

        tol =
            "Insert into Result values ('"
                + a
                + "','"
                + b
                + "','"
                + c
                + "','"
                + f
                + "','"
                + g
                + "','"
                + h
                + "','"
                + j
                + "','"
                + k
                + "','"
                + l
                + "','"
                + m
                + "','"
                + n
                + "','"
                + o
                + "','"
                + p
                + "')";
      }
      try {
        stm.executeUpdate(tol);
      } catch (Exception error) {
        System.out.println(error);
      }
    }

    if (e.getSource() == b2) // **** DELETE BUTTON ****//
    {
      if (name == "Student") {
        b = t2.getText();
        tol = "Delete from Student where Id = '" + b + "'";
      }

      if (name == "Teacher") {
        b = t12.getText();
        tol = "Delete from Teacher where Id = '" + b + "'";
      }

      if (name == "Course") {
        b = t8.getText();
        tol = "Delete from Course where Id = '" + b + "'";
      }

      if (name == "Result") {
        b = t16.getText();
        tol = "Delete from Result where Code = '" + b + "'";
      }
      try {
        stm.executeUpdate(tol);
      } catch (Exception error) {
        System.out.println(error);
      }
    }

    if (e.getSource() == b3) // **** UPDATE BUTTON ****//
    {
      if (name == "Student") {
        a = t1.getText();
        b = t2.getText();
        c = t3.getText();
        f = t4.getText();
        g = t5.getText();
        h = t6.getText();

        tol =
            "Update Student set Name = '"
                + a
                + "', ID = '"
                + b
                + "', Dept = '"
                + c
                + "', CGPA = '"
                + f
                + "', Address = '"
                + g
                + "', Cell = '"
                + h
                + "' where ID = '"
                + b
                + "'";
      }

      if (name == "Teacher") {
        a = t11.getText();
        b = t12.getText();
        c = t13.getText();
        f = t14.getText();

        tol =
            "Update Teacher set Name = '"
                + a
                + "', ID = '"
                + b
                + "', Dept = '"
                + c
                + "', Course = '"
                + f
                + "' where ID = '"
                + b
                + "'";
      }

      if (name == "Course") {
        a = t7.getText();
        b = t8.getText();
        c = t9.getText();
        f = t0.getText();

        tol =
            "Update Course set Name = '"
                + a
                + "', Code = '"
                + b
                + "', Credit = '"
                + c
                + "', Prerecusite = '"
                + f
                + "' where Code = '"
                + b
                + "'";
      }

      if (name == "Result") {
        a = t15.getText();
        b = t16.getText();
        c = t17.getText();
        f = t18.getText();
        g = t19.getText();
        h = t20.getText();
        j = t21.getText();
        k = t22.getText();
        l = t23.getText();
        m = t24.getText();
        n = t25.getText();
        o = t26.getText();
        p = t27.getText();

        tol =
            "Update Result set Course = '"
                + a
                + "', Code = '"
                + b
                + "', Credit = '"
                + c
                + "', A = '"
                + f
                + "', B+ = '"
                + g
                + "', B = '"
                + h
                + "', C+ = '"
                + j
                + "', C = '"
                + k
                + "', D+ = '"
                + l
                + "', D = '"
                + m
                + "', F = '"
                + n
                + "', I = '"
                + o
                + "', W = '"
                + p
                + "' where Code = '"
                + b
                + "'";
        // JOptionPane.showMessageDialog(null,tol,null,JOptionPane.PLAIN_MESSAGE);
        // tol = "Update Result set Course = '"+a+"', Code = '"+b+"', Credit = '"+c+"' where Code =
        // '"+b+"'";
      }
      try {
        stm.executeUpdate(tol);
      } catch (Exception error) {
        System.out.println(error);
      }
    }

    if (e.getSource() == b4) // **** NEXT BUTTON ****//
    {
      if (name == "Student") {
        try {
          if (rs.next()) {
            t1.setText(rs.getString(1));
            t2.setText(rs.getString(2));
            t3.setText(rs.getString(3));
            t4.setText(rs.getString(4));
            t5.setText(rs.getString(5));
            t6.setText(rs.getString(6));
          }
        } catch (Exception error) {
          System.out.println(error);
        }
      }

      if (name == "Teacher") {
        try {
          if (rs.next()) {
            t11.setText(rs.getString(1));
            t12.setText(rs.getString(2));
            t13.setText(rs.getString(3));
            t14.setText(rs.getString(4));
          }
        } catch (Exception error) {
          System.out.println(error);
        }
      }

      if (name == "Course") {
        try {
          if (rs.next()) {
            t7.setText(rs.getString(1));
            t8.setText(rs.getString(2));
            t9.setText(rs.getString(3));
            t0.setText(rs.getString(4));
          }
        } catch (Exception error) {
          System.out.println(error);
        }
      }

      if (name == "Result") {
        try {
          if (rs.next()) {
            t15.setText(rs.getString(1));
            t16.setText(rs.getString(2));
            t17.setText(rs.getString(3));
            t18.setText(rs.getString(4));
            t19.setText(rs.getString(5));
            t20.setText(rs.getString(6));
            t21.setText(rs.getString(7));
            t22.setText(rs.getString(8));
            t23.setText(rs.getString(9));
            t24.setText(rs.getString(10));
            t25.setText(rs.getString(11));
            t26.setText(rs.getString(12));
            t27.setText(rs.getString(13));
          }
        } catch (Exception error) {
          System.out.println(error);
        }
      }
    }

    if (e.getSource() == b5) // **** PREVIOUS BUTTON ****//
    {
      if (name == "Student") {
        try {
          if (rs.previous()) {
            t1.setText(rs.getString(1));
            t2.setText(rs.getString(2));
            t3.setText(rs.getString(3));
            t4.setText(rs.getString(4));
            t5.setText(rs.getString(5));
            t6.setText(rs.getString(6));
          }
        } catch (Exception error) {
          System.out.println(error);
        }
      }

      if (name == "Teacher") {
        try {
          if (rs.previous()) {
            t11.setText(rs.getString(1));
            t12.setText(rs.getString(2));
            t13.setText(rs.getString(3));
            t14.setText(rs.getString(4));
          }
        } catch (Exception error) {
          System.out.println(error);
        }
      }

      if (name == "Course") {
        try {
          if (rs.previous()) {
            t7.setText(rs.getString(1));
            t8.setText(rs.getString(2));
            t9.setText(rs.getString(3));
            t0.setText(rs.getString(4));
          }
        } catch (Exception error) {
          System.out.println(error);
        }
      }

      if (name == "Result") {
        try {
          if (rs.previous()) {
            t15.setText(rs.getString(1));
            t16.setText(rs.getString(2));
            t17.setText(rs.getString(3));
            t18.setText(rs.getString(4));
            t19.setText(rs.getString(5));
            t20.setText(rs.getString(6));
            t21.setText(rs.getString(7));
            t22.setText(rs.getString(8));
            t23.setText(rs.getString(9));
            t24.setText(rs.getString(10));
            t25.setText(rs.getString(11));
            t26.setText(rs.getString(12));
            t27.setText(rs.getString(13));
          }
        } catch (Exception error) {
          System.out.println(error);
        }
      }
    }
  }
Beispiel #15
0
  public void actionPerformed(ActionEvent evt) {
    String arg = evt.getActionCommand();
    if (arg.equals("Query")) { // 用户按下Query按钮
      ResultSet rs = null;
      try {
        String author = (String) authors.getSelectedItem();
        String publisher = (String) publishers.getSelectedItem();
        if (!author.equals("Any") && !publisher.equals("Any")) {
          if (authorPublisherQueryStmt == null) {
            //  根据用户选择的出版社名和作者名查询相关的书名和书价
            String authorPublisherQuery =
                "SELECT Books.Price, Books.Title "
                    + "FROM Books, BooksAuthors, Authors, Publishers "
                    + "WHERE Authors.Author_Id = BooksAuthors.Author_Id AND "
                    + "BooksAuthors.ISBN = Books.ISBN AND "
                    + "Books.Publisher_Id = Publishers.Publisher_Id AND "
                    + "Authors.Name = ? AND "
                    + "Publishers.Name = ?";
            authorPublisherQueryStmt = con.prepareStatement(authorPublisherQuery);
          }

          authorPublisherQueryStmt.setString(1, author);
          authorPublisherQueryStmt.setString(2, publisher);
          rs = authorPublisherQueryStmt.executeQuery();
        } else if (!author.equals("Any") && publisher.equals("Any")) {
          if (authorQueryStmt == null) {
            //  根据用户选择的作者名查询相关的书名和书价
            String authorQuery =
                "SELECT Books.Price, Books.Title "
                    + "FROM Books, BooksAuthors, Authors "
                    + "WHERE Authors.Author_Id = BooksAuthors.Author_Id AND "
                    + "BooksAuthors.ISBN = Books.ISBN AND "
                    + "Authors.Name = ?";
            authorQueryStmt = con.prepareStatement(authorQuery);
          }
          authorQueryStmt.setString(1, author);
          rs = authorQueryStmt.executeQuery();
        } else if (author.equals("Any") && !publisher.equals("Any")) {
          if (publisherQueryStmt == null) {
            //  根据用户选择的出版社名查询相关的书名和书价
            String publisherQuery =
                "SELECT Books.Price, Books.Title "
                    + "FROM Books, Publishers "
                    + "WHERE Books.Publisher_Id = Publishers.Publisher_Id AND "
                    + "Publishers.Name = ?";
            publisherQueryStmt = con.prepareStatement(publisherQuery);
          }
          publisherQueryStmt.setString(1, publisher);
          rs = publisherQueryStmt.executeQuery();
        } else {
          if (allQueryStmt == null) {
            // 若用户未选任何信息,则输出所有的书名和对应的书价
            String allQuery = "SELECT Books.Price, Books.Title FROM Books";
            allQueryStmt = con.prepareStatement(allQuery);
          }
          rs = allQueryStmt.executeQuery();
        }

        result.setText("");
        while (rs.next()) result.append(rs.getString(1) + " | " + rs.getString(2) + "\n");
        rs.close();
      } catch (Exception e) {
        result.setText("Error " + e);
      }
    } else if (arg.equals("Change prices")) { //  用户选择“Change prices”按钮
      String publisher = (String) publishers.getSelectedItem();
      if (publisher.equals("Any")) result.setText("I am sorry, but I cannot do that.");
      else
        try {
          // 根据用户输入的新的书价更新Books表的数据
          String updateStatement =
              "UPDATE Books "
                  + "SET Price = Price + "
                  + priceChange.getText()
                  + " WHERE Books.Publisher_Id = "
                  + "(SELECT Publisher_Id FROM Publishers WHERE Name = '"
                  + publisher
                  + "')";
          int r = stmt.executeUpdate(updateStatement);
          result.setText(r + " records updated.");
        } catch (Exception e) {
          result.setText("Error " + e);
        }
    }
  }
Beispiel #16
0
  public static void makeRoomTables() {
    String tableDay = "";
    int leap_year_days = 28;
    String year = "2015";
    int leap = Integer.parseInt(year.trim());

    if ((leap % 400 == 0) || ((leap % 4 == 0) && (leap % 100 != 0))) {
      leap_year_days = 29;
    } else {
    }
    String[] month = new String[13];
    // populate array
    month[1] = "01";
    month[2] = "02";
    month[3] = "03";
    month[4] = "04";
    month[5] = "05";
    month[6] = "06";
    month[7] = "07";
    month[8] = "08";
    month[9] = "09";
    month[10] = "10";
    month[11] = "11";
    month[12] = "12";

    try {

      Connection con =
          DriverManager.getConnection(
              "jdbc:mysql://67.20.111.85:3306/jeehtove_caliking?relaxAutoCommit=true",
              "jeehtove_ck",
              "Z_^PBBZT+kcy");
      Statement stmt_query = con.createStatement();
      Statement stmt_addroomdata = con.createStatement();

      for (int i = 1; i <= 12; i++) {
        if (month[i] == "01"
            || month[i] == "03"
            || month[i] == "05"
            || month[i] == "07"
            || month[i] == "08"
            || month[i] == "10"
            || month[i] == "12") {
          for (int j = 1; j <= 31; j++) {
            if (j >= 1 && j <= 9) {
              tableDay = year + "_" + month[i] + "_0" + j;
            } else tableDay = year + "_" + month[i] + "_" + j;
            String query =
                "CREATE TABLE if not exists jeehtove_caliking.rooms_"
                    + tableDay
                    + "(`ROOM` int(11) NOT NULL,`TYPE` int(11) NOT NULL,`BOOKED` int(11) NOT NULL DEFAULT '0') ENGINE=MyISAM DEFAULT CHARSET=latin1;";
            String tableData =
                "INSERT INTO `rooms_"
                    + tableDay
                    + "` (`ROOM`, `TYPE`, `BOOKED`) VALUES (101, 1, 0), (102, 1, 0), (103, 1, 0), (104, 1, 0), (105, 1, 0), (106, 1, 0), (107, 1, 0), (108, 1, 0), (109, 1, 0), (110, 2, 0), (111, 2, 0), (112, 2, 0), (113, 2, 0), (114, 2, 0), (115, 2, 0), (116, 2, 0), (117, 2, 0), (118, 2, 0), (119, 3, 0);";

            int maketables = stmt_query.executeUpdate(query);
            int addroomdata = stmt_addroomdata.executeUpdate(tableData);
            System.out.println("Room Tables Created for " + tableDay + ".");
          }
        }

        if (month[i] == "04" || month[i] == "06" || month[i] == "09" || month[i] == "11") {
          for (int j = 1; j <= 30; j++) {
            if (j >= 1 && j <= 9) {
              tableDay = year + "_" + month[i] + "_0" + j;
            } else tableDay = year + "_" + month[i] + "_" + j;
            String query =
                "CREATE TABLE if not exists jeehtove_caliking.rooms_"
                    + tableDay
                    + "(`ROOM` int(11) NOT NULL,`TYPE` int(11) NOT NULL,`BOOKED` int(11) NOT NULL DEFAULT '0') ENGINE=MyISAM DEFAULT CHARSET=latin1;";
            String tableData =
                "INSERT INTO `rooms_"
                    + tableDay
                    + "` (`ROOM`, `TYPE`, `BOOKED`) VALUES (101, 1, 0), (102, 1, 0), (103, 1, 0), (104, 1, 0), (105, 1, 0), (106, 1, 0), (107, 1, 0), (108, 1, 0), (109, 1, 0), (110, 2, 0), (111, 2, 0), (112, 2, 0), (113, 2, 0), (114, 2, 0), (115, 2, 0), (116, 2, 0), (117, 2, 0), (118, 2, 0), (119, 3, 0);";

            int maketables = stmt_query.executeUpdate(query);
            int addroomdata = stmt_addroomdata.executeUpdate(tableData);
            System.out.println("Room Tables Created for " + tableDay + ".");
          }
        }

        if (month[i] == "02") {
          for (int j = 1; j <= leap_year_days; j++) {
            if (j >= 1 && j <= 9) {
              tableDay = year + "_" + month[i] + "_0" + j;
            } else tableDay = year + "_" + month[i] + "_" + j;
            String query =
                "CREATE TABLE if not exists jeehtove_caliking.rooms_"
                    + tableDay
                    + "(`ROOM` int(11) NOT NULL,`TYPE` int(11) NOT NULL,`BOOKED` int(11) NOT NULL DEFAULT '0') ENGINE=MyISAM DEFAULT CHARSET=latin1;";
            String tableData =
                "INSERT INTO `rooms_"
                    + tableDay
                    + "` (`ROOM`, `TYPE`, `BOOKED`) VALUES (101, 1, 0), (102, 1, 0), (103, 1, 0), (104, 1, 0), (105, 1, 0), (106, 1, 0), (107, 1, 0), (108, 1, 0), (109, 1, 0), (110, 2, 0), (111, 2, 0), (112, 2, 0), (113, 2, 0), (114, 2, 0), (115, 2, 0), (116, 2, 0), (117, 2, 0), (118, 2, 0), (119, 3, 0);";

            int maketables = stmt_query.executeUpdate(query);
            int addroomdata = stmt_addroomdata.executeUpdate(tableData);
            System.out.println("Room Tables Created for " + tableDay + ".");
          }
        }
      }

      System.out.println("Table creation has been completed.");

    } catch (Exception e) {
      System.out.println(e);
    }
  }
Beispiel #17
0
  public void bookRoom() {
    try {
      int code = 0;
      Connection con =
          DriverManager.getConnection(
              "jdbc:mysql://67.20.111.85:3306/jeehtove_caliking?relaxAutoCommit=false",
              "jeehtove_ck",
              "Z_^PBBZT+kcy");
      Statement stmt_insert = con.createStatement();
      Statement stmt_tableRange = con.createStatement();
      Statement stmt_checkrooms = con.createStatement();
      Statement stmt_checkrooms_2 = con.createStatement();

      String insert = null;
      int flag = 0;

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

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

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

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

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

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

      stmt_tableRange.close();

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

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

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

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

      // else System.out.println("All " + room_type + " rooms are booked for the time requested.");
      System.out.println("Complete.");
    } catch (Exception e) {
      System.out.println(e);
    }
  }
  private void insertRows(Connection connection) {
    // Build the SQL INSERT statement
    String sqlInsert = "insert into " + jtfTableName.getText() + " values (";

    // Use a Scanner to read text from the file
    Scanner input = null;

    // Get file name from the text field
    String filename = jtfFilename.getText().trim();

    try {
      // Create a scanner
      input = new Scanner(new File(filename));

      // Create a statement
      Statement statement = connection.createStatement();

      System.out.println(
          "Driver major version? " + connection.getMetaData().getDriverMajorVersion());

      // Determine if batchUpdatesSupported is supported
      boolean batchUpdatesSupported = false;

      try {
        if (connection.getMetaData().supportsBatchUpdates()) {
          batchUpdatesSupported = true;
          System.out.println("batch updates supported");
        } else {
          System.out.println(
              "The driver is of JDBC 2 type, but " + "does not support batch updates");
        }
      } catch (UnsupportedOperationException ex) {
        System.out.println("The driver does not support JDBC 2");
      }

      // Determine if the driver is capable of batch updates
      if (batchUpdatesSupported) {
        // Read a line and add the insert table command to the batch
        while (input.hasNext()) {
          statement.addBatch(sqlInsert + input.nextLine() + ")");
        }

        statement.executeBatch();

        jlblStatus.setText("Batch updates completed");
      } else {
        // Read a line and execute insert table command
        while (input.hasNext()) {
          statement.executeUpdate(sqlInsert + input.nextLine() + ")");
        }

        jlblStatus.setText("Single row update completed");
      }
    } catch (SQLException ex) {
      System.out.println(ex);
    } catch (FileNotFoundException ex) {
      System.out.println("File not found: " + filename);
    } catch (IOException ex) {
      ex.printStackTrace();
    } finally {
      if (input != null) input.close();
    }
  }