Advertisement
Guest User

Untitled

a guest
May 20th, 2016
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.11 KB | None | 0 0
  1. // Declaring database connection settings.. *java* is the database name, hence all operations will be performed in this db.
  2.  
  3. String url = "jdbc:mysql://localhost:3306/java";
  4. String user = "root";
  5. String pw = "";
  6.  
  7.  
  8.  
  9. /* You implement an action listener to the button Delete (btnDelete) which defines what should be done when a user performs certain *operation.. The operation may be when a user clicks a button, chooses a menu item or presses Enter in a text field.
  10. * The actionPerformed is the method that executes the action when a user clicks the button (btnDelete). Here you are deleting a supplier.
  11.  
  12.         btnDelete.addActionListener(new ActionListener() {
  13.             public void actionPerformed(ActionEvent e) {
  14.  
  15.                 try {
  16.                    
  17.                     Class.forName("com.mysql.jdbc.Driver"); //register the JDBC Driver
  18.                    
  19.                     Connection con = DriverManager.getConnection(url, user, pw); //establish the db connection
  20.                                        
  21.                     String del = "DELETE FROM supplier WHERE SupplierID = ?"; // SQL Query to delete the a supplier by a Supplier ID
  22.                    
  23.                     PreparedStatement pstmt = con.prepareStatement(del); // using a prepared statement to achieve this
  24.                    
  25.                     int id =   Integer.parseInt(txtSupplierId.getText()); // get the supplier ID from the text field. Since the ID is an Integer in the DB, the textfield returns us the ID as a String. Hence, we convert it to Integer using Integer.parseInt(...
  26.                            
  27.                     pstmt.setInt(1, id); // we set the parameter index from the SQL Query where there is a ? in the SQL Query above
  28.                    
  29.                     pstmt.execute(); // runs the query within java
  30.                    
  31.                 JOptionPane.showMessageDialog(null, "Deleted"); // display a successful msg if deleted./
  32.                 } catch (Exception err) {
  33.                     JOptionPane.showMessageDialog(Supplier.this, err.getMessage()); // catches the error if the delete is not successful..
  34.                 }
  35.  
  36.             }
  37.         });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement