Esempio n. 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.");
      }
    }
Esempio n. 2
0
 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
Esempio n. 3
0
  /**
   * _more_
   *
   * @return _more_
   */
  public Connection getConnection() {
    if (connection != null) {
      return connection;
    }
    String url = getFilename();
    if ((dataSource.getUserName() == null) || (dataSource.getUserName().trim().length() == 0)) {
      if (url.indexOf("?") >= 0) {
        int idx = url.indexOf("?");
        List<String> args =
            (List<String>) StringUtil.split(url.substring(idx + 1), "&", true, true);
        url = url.substring(0, idx);
        for (String tok : args) {
          List<String> subtoks = (List<String>) StringUtil.split(tok, "=", true, true);
          if (subtoks.size() != 2) {
            continue;
          }
          String name = subtoks.get(0);
          String value = subtoks.get(1);
          if (name.equals("user")) {
            dataSource.setUserName(value);
          } else if (name.equals("password")) {
            dataSource.setPassword(value);
          }
        }
      }
    }

    int cnt = 0;
    while (true) {
      String userName = dataSource.getUserName();
      String password = dataSource.getPassword();
      if (userName == null) {
        userName = "";
      }
      if (password == null) {
        password = "";
      }
      try {
        connection = DriverManager.getConnection(url, userName, password);
        return connection;
      } catch (SQLException sqe) {
        if ((sqe.toString().indexOf("role \"" + userName + "\" does not exist") >= 0)
            || (sqe.toString().indexOf("user name specified") >= 0)) {
          String label;
          if (cnt == 0) {
            label =
                "<html>The database requires a login.<br>Please enter a user name and password:</html>";
          } else {
            label = "<html>Incorrect username/password. Please try again.</html>";
          }
          if (!dataSource.showPasswordDialog("Database Login", label)) {
            return null;
          }
          cnt++;
          continue;
        }
        throw new BadDataException("Unable to connect to database", sqe);
      }
    }
  }
Esempio n. 4
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);
    }
  }
Esempio n. 5
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
  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!");
    }
  }
Esempio n. 7
0
 public void initDB(String url) {
   try {
     db = DriverManager.getConnection(url);
     statement = db.createStatement();
   } catch (Exception e) {
     System.out.println("Database could not started");
     e.printStackTrace();
   }
 } // initDB sonu
Esempio n. 8
0
  public static void goer() throws Exception {

    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection con =
        (Connection) DriverManager.getConnection("jdbc:oracle:thin:@localhost", "system", "system");
    String query2 = "select * from logger";
    Statement st2 = con.createStatement();
    ResultSet rs = st2.executeQuery(query2);
    boolean b = false;
    while (rs.next()) {
      if ((rs.getString(3)).equals(p2.str3)) {
        b = true;
      }
    }
    if (b == false) {
      String query1 =
          "insert into logger values('"
              + p2.str1
              + "','"
              + p2.str2
              + "','"
              + p2.str3
              + "','"
              + p2.str4
              + "','"
              + p2.str5
              + "','"
              + p2.str7
              + "','"
              + p2.str8
              + "','"
              + p2.str9
              + "','"
              + p2.str13
              + "')";
      Statement st1 = con.createStatement();
      st1.executeQuery(query1);
      JOptionPane.showMessageDialog(null, "welcome\n now you are a meber of our team ");
    } else {
      JOptionPane.showMessageDialog(null, "this username already exist");
    }
  }
Esempio n. 9
0
 public void koneksiDatabase() {
   try {
     String url = "jdbc:mysql://localhost:3306/payroll_db";
     Properties prop = new Properties();
     prop.put("user", "root");
     prop.put("password", "admin");
     konek = DriverManager.getConnection(url, prop);
     status_Proses(true, "Sukses!!!Berhasil Terhubung dengan Database...", 20);
   } catch (SQLException se) {
     status_Proses(false, "Gagal!!!Tidak terhubung \nKarena : " + se, 20);
   }
 }
Esempio n. 10
0
    public void actionPerformed(ActionEvent e) {
      String name4 = JOptionPane.showInputDialog("Enter the UserId:");
      String name5 = JOptionPane.showInputDialog("Enter the DOB(dd/mm/yyyy):");
      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 userid='" + name4 + "' and dob='" + name5 + "'");
        rs.next();
        String z = rs.getString("password");
        JOptionPane.showMessageDialog(null, "Your  Password  is  <  " + z + "  >");

      } catch (Exception ex) {
        System.out.print(ex);
        JOptionPane.showMessageDialog(null, "Please Enter valid UserId and DOB(dd/mm/yyyy) .");
      }
    }
Esempio n. 11
0
  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");
    }
  }
 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);
        }
      }
    }
  }
Esempio n. 14
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 .");
   }
 }
Esempio n. 15
0
  /** 利用属性文件中的信息连接数据库 * */
  public static Connection getConnection() throws SQLException, IOException {
    Properties props = new Properties();
    String fileName = "QueryDB.properties";
    FileInputStream in = new FileInputStream(fileName);
    props.load(in);

    String drivers = props.getProperty("jdbc.drivers");
    if (drivers != null) System.setProperty("jdbc.drivers", drivers);
    String url = props.getProperty("jdbc.url");
    String username = props.getProperty("jdbc.username");
    String password = props.getProperty("jdbc.password");

    return DriverManager.getConnection(url, username, password);
  }
Esempio n. 16
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);
    }
  }
Esempio n. 18
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");
    }
  }
Esempio n. 19
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.");
      }
    }
Esempio n. 20
0
 public static Connection getConnect() {
   try {
     /*if (!getConnect) {
     if (!con.isValid(1)) {*/
     String host = "jdbc:mysql://localhost:3306/2761DB";
     String uname = "root";
     String upassword = "******";
     con = DriverManager.getConnection(host, uname, upassword);
     getConnect = true;
     /*}
     }*/
   } catch (SQLException err) {
     System.out.println(err.getMessage());
   }
   return con;
 }
Esempio n. 21
0
  private void copyFile() throws Exception {
    // Load the JDBC driver
    Class.forName(((String) jcboDriver.getSelectedItem()).trim());
    System.out.println("Driver loaded");

    // Establish a connection
    Connection conn =
        DriverManager.getConnection(
            ((String) jcboURL.getSelectedItem()).trim(),
            jtfUsername.getText().trim(),
            String.valueOf(jtfPassword.getPassword()).trim());
    System.out.println("Database connected");

    // Read each line from the text file and insert it to the table
    insertRows(conn);
  }
Esempio n. 22
0
 // 采用静态初始化块来初始化Connection、Statement对象
 static {
   try {
     Properties props = new Properties();
     props.load(new FileInputStream("mysql.ini"));
     String drivers = props.getProperty("driver");
     String url = props.getProperty("url");
     String username = props.getProperty("user");
     String password = props.getProperty("pass");
     // 加载数据库驱动
     Class.forName(drivers);
     // 取得数据库连接
     conn = DriverManager.getConnection(url, username, password);
     stmt = conn.createStatement();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Esempio n. 23
0
  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
Esempio n. 24
0
  // event handling
  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == btnok) {
      PreparedStatement pstm;
      ResultSet rs;
      String sql;
      // if no entries has been made and hit ok button throw an error
      // you can do this step using try clause as well
      if ((tf1.getText().equals("") && (tf2.getText().equals("")))) {
        lblmsg.setText("Enter your details ");
        lblmsg.setForeground(Color.magenta);
      } else {

        try {
          Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
          Connection connect = DriverManager.getConnection("jdbc:odbc:student_base");
          System.out.println("Connected to the database");
          pstm = connect.prepareStatement("insert into student_base values(?,?)");
          pstm.setString(1, tf1.getText());
          pstm.setString(2, tf2.getText());
          // execute method to execute the query
          pstm.executeUpdate();
          lblmsg.setText("Details have been added to database");

          // closing the prepared statement  and connection object
          pstm.close();
          connect.close();
        } catch (SQLException sqe) {
          System.out.println("SQl error");
        } catch (ClassNotFoundException cnf) {
          System.out.println("Class not found error");
        }
      }
    }
    // upon clickin button addnew , your textfield will be empty to enternext record
    if (e.getSource() == btnaddnew) {
      tf1.setText("");
      tf2.setText("");
    }

    if (e.getSource() == btnexit) {
      System.exit(1);
    }
  }
Esempio n. 25
0
 private static Connection getConnection() {
   Connection con = null;
   try {
     Class.forName("com.mysql.jdbc.Driver");
     String url = "jdbc:mysql://localhost:3306/SMS";
     String user = "******";
     String pw = "";
     con = DriverManager.getConnection(url, user, pw);
   } catch (ClassNotFoundException e) {
     System.out.println("Unable to locate class");
     System.out.println(e.getMessage());
     JOptionPane.showMessageDialog(null, " Database not connected");
     // System.exit(0);
   } catch (SQLException e) {
     System.out.println(e.getMessage());
     JOptionPane.showMessageDialog(null, " Database not connected");
     // System.exit(0);
   }
   return con;
 }
Esempio n. 26
0
  public void FillList() {
    try {

      String sql1 = "select  * from motors";
      Class.forName("com.mysql.jdbc.Driver");
      Connection con =
          (Connection)
              DriverManager.getConnection("jdbc:mysql://localhost:3306/bharatmotors", "root", "");
      Statement stmt = con.createStatement();
      ResultSet rs1 = stmt.executeQuery(sql1);
      DefaultListModel DLM = new DefaultListModel();

      while (rs1.next()) {
        DLM.addElement(rs1.getString(3));
        // DLM.addElement(rs1.getString(2));
      }

      List.setModel(DLM);
    } catch (Exception e) {
      JOptionPane.showMessageDialog(null, "e.getString()");
    }
  }
Esempio n. 27
0
  public void login() {
    String driver = "oracle.jdbc.driver.OracleDriver";
    String url = "jdbc:oracle:thin:@localhost:1521:orcl";
    Connection con = null;
    Statement stmt = null;
    ResultSet rs = null;

    String id, pw, sql;
    try {
      Class.forName(driver);
      con = DriverManager.getConnection(url, "hr", "hr");
      stmt = con.createStatement();
      sql = "select * from chatuser where id = '" + lid.getText() + "'";
      rs = stmt.executeQuery(sql);
      if (rs.next()) {
        pw = rs.getString(2);
        nick = rs.getString(3);
        if (lpw.getText().equals(pw)) {
          jd.setVisible(false);
          setVisible(true);
        } else {
          lpw.setText("일치하지 않습니다.");
        }
      } else {
        lid.setText("일치하지 않습니다.");
      }
    } catch (Exception e1) {
      e1.printStackTrace();
      System.out.println("데이터 베이스 연결 실패!!");
    } finally {
      try {
        if (rs != null) rs.close();
        if (stmt != null) stmt.close();
        if (con != null) con.close();
      } catch (Exception e1) {
        System.out.println(e1.getMessage());
      }
    }
  }
Esempio n. 28
0
 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
Esempio n. 29
0
  public General_Info() {

    pic.setIcon(userPic);
    String url = "jdbc:odbc:lib";

    try {
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      connection = DriverManager.getConnection(url);
    } catch (ClassNotFoundException cnfex) {
      System.err.println("Failed to load driver");
      cnfex.printStackTrace();
      System.exit(1);
    } catch (SQLException sqlex) {
      System.err.println("unable to connect");
      sqlex.printStackTrace();
    }

    // validation for telephone
    tel_text.addKeyListener(
        new KeyAdapter() {
          public void keyTyped(KeyEvent e) {
            char c = e.getKeyChar();
            if (!((Character.isDigit(c)
                || (c == KeyEvent.VK_BACK_SPACE)
                || (c == KeyEvent.VK_DELETE)))) {
              getToolkit().beep();
              e.consume();
            }
          }
        });

    // validation for fax
    fax_text.addKeyListener(
        new KeyAdapter() {
          public void keyTyped(KeyEvent e) {
            char c = e.getKeyChar();
            if (!((Character.isDigit(c)
                || (c == KeyEvent.VK_BACK_SPACE)
                || (c == KeyEvent.VK_DELETE)))) {
              getToolkit().beep();
              e.consume();
            }
          }
        });

    patron_text.setText("P-");
    patron_text.addFocusListener(
        new MyActionListener() {
          public void focusLost(FocusEvent e) {

            try {
              Statement statement = connection.createStatement();

              String query2 =
                  "SELECT * FROM patronmaster " + "WHERE id = '" + patron_text.getText() + "'";

              ResultSet rs2 = statement.executeQuery(query2);
              int cnt = 0;
              while (rs2.next()) {
                cnt++;
              }
              if (cnt != 0) {

                try {
                  userPic = new ImageIcon(patron_text.getText() + ".gif");
                  pic.setIcon(userPic);
                } catch (Exception ex) {
                  ex.printStackTrace();
                  pic.setIcon(userPic);
                }

                String query1 =
                    "SELECT * FROM patronmaster " + "WHERE id = '" + patron_text.getText() + "'";

                ResultSet rs1 = statement.executeQuery(query1);
                try {
                  rs1.next();

                  int confirm =
                      JOptionPane.showConfirmDialog(
                          null,
                          "This record Exists, would you like to update it?",
                          "CONFIRM",
                          JOptionPane.YES_NO_OPTION);
                  if (confirm == JOptionPane.NO_OPTION) {
                    patron_text.setEditable(false);
                    name_text.setEditable(false);
                    passport_text.setEditable(false);
                    expiry_date_text.setEditable(false);
                    reg_by_text.setEditable(false);
                    reg_date_text.setEditable(false);
                    textArea.setEditable(false);
                    tel_text.setEditable(false);
                    fax_text.setEditable(false);
                    email_text.setEditable(false);
                  } else {

                  }
                  name_text.setText(rs1.getString(2));
                  passport_text.setText(rs1.getString(3));
                  expiry_date_text.setText(rs1.getString(6));
                  reg_by_text.setText(rs1.getString(7));
                  reg_date_text.setText(rs1.getString(8));
                  textArea.setText(rs1.getString(9));
                  tel_text.setText(rs1.getString(10));
                  fax_text.setText(rs1.getString(11));
                  email_text.setText(rs1.getString(12));
                  status_combo.setSelectedItem(rs1.getString(4));
                  salute_combo.setSelectedItem(rs1.getString(5));
                  group_combo.setSelectedItem(rs1.getString(13));

                  statement.close();

                } catch (SQLException sqlex) {
                  pic.setIcon(userPic);
                }
              }
            } catch (SQLException sqlex) {
              pic.setIcon(userPic);
            }
          }
        });

    scroll.add(address);
    scroll.add(scrollPane);

    text.setLayout(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();

    gbc.gridy = 0;
    gbc.gridx = 0;
    text.add(tel, gbc);
    gbc.gridy = 1;
    text.add(fax, gbc);
    gbc.gridy = 2;
    text.add(email, gbc);
    gbc.gridy = 0;
    gbc.gridx = 2;
    text.add(tel_text, gbc);
    gbc.gridy = 1;
    text.add(fax_text, gbc);
    gbc.gridy = 2;
    text.add(email_text, gbc);

    pic.setSize(50, 50);
    pane1.add(scroll, BorderLayout.CENTER);
    pane1.add(pic, BorderLayout.EAST);
    pane1.add(text, BorderLayout.WEST);

    add(pane1);
  }
Esempio n. 30
0
  /** Initialize the contents of the frame. */
  private void initialize() {

    JPanel mainPanel = new JPanel();

    JButton book = new JButton("Book");
    mainPanel.add(book);
    book.setPreferredSize(new Dimension(200, 80));

    JTextField enterFlightNum = new JTextField("Enter Flight Number");
    enterFlightNum.setColumns(10);
    enterFlightNum.setBounds(227, 251, 286, 42);
    mainPanel.add(enterFlightNum);

    JButton mainMenu = new JButton("Main Menu");
    mainPanel.add(mainMenu);
    mainMenu.setPreferredSize(new Dimension(200, 80));
    mainMenu.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {

            fFrame.setVisible(false);
            new MainUI(c1);
          }
        });

    book.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {

            try {
              c1.bookFlight(Integer.parseInt(enterFlightNum.getText()));
              ;
            } catch (Exception ex) {

              ex.printStackTrace();
            }
          }
        });

    JPanel mainPanel2 = new JPanel();
    JLabel listFlights = new JLabel();
    mainPanel2.add(listFlights);

    Connection connection;
    String labelText = "<html>";
    try {
      Class.forName("com.mysql.jdbc.Driver");
      System.out.println("Driver loaded");

      connection = DriverManager.getConnection("jdbc:mysql://localhost/mydb", "CIS3270", "Cis3270");

      System.out.println("Connection complete");

      Statement statement;

      statement = connection.createStatement();

      String queryString = "select * from flight";

      ResultSet rs = statement.executeQuery(queryString);

      while (rs.next()) {

        labelText =
            labelText
                + rs.getString(1)
                + " "
                + rs.getString(3)
                + " "
                + rs.getString(4)
                + " "
                + rs.getString(5)
                + " "
                + rs.getString(6)
                + "<br>";
      }

    } catch (Exception e) {

    }

    listFlights.setText(labelText);
    System.out.println(labelText);

    JPanel mainCombine = new JPanel();
    mainCombine.add(mainPanel, BorderLayout.NORTH);
    mainCombine.add(mainPanel2, BorderLayout.SOUTH);

    fFrame = new JFrame();
    fFrame.setSize(1000, 800);
    fFrame.add(mainCombine);
    fFrame.setVisible(true);
    fFrame.setResizable(false);
    fFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    fFrame.getContentPane().setLayout(null);
  }