Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Declaring database connection settings.. *java* is the database name, hence all operations will be performed in this db.
- String url = "jdbc:mysql://localhost:3306/java";
- String user = "root";
- String pw = "";
- /* 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.
- * The actionPerformed is the method that executes the action when a user clicks the button (btnDelete). Here you are deleting a supplier.
- btnDelete.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- try {
- Class.forName("com.mysql.jdbc.Driver"); //register the JDBC Driver
- Connection con = DriverManager.getConnection(url, user, pw); //establish the db connection
- String del = "DELETE FROM supplier WHERE SupplierID = ?"; // SQL Query to delete the a supplier by a Supplier ID
- PreparedStatement pstmt = con.prepareStatement(del); // using a prepared statement to achieve this
- 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(...
- pstmt.setInt(1, id); // we set the parameter index from the SQL Query where there is a ? in the SQL Query above
- pstmt.execute(); // runs the query within java
- JOptionPane.showMessageDialog(null, "Deleted"); // display a successful msg if deleted./
- } catch (Exception err) {
- JOptionPane.showMessageDialog(Supplier.this, err.getMessage()); // catches the error if the delete is not successful..
- }
- }
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement