Java & Netbeans: Save, Update, Delete Data from MySQL

The following code below help you on how to save, update, and delete data using your Java with Netbeans IDE with MySQL database. To do Save, Update and Delete data, Please follow the steps below.

Add this declaration code inside your class.

Connection conn=null;
ResultSet rs = null;
PreparedStatement pst=null;

 Insert this code inside your public methods after the initialize components of “initComponents();”. Your MySQL connection must be external or separate class.

conn=yourclassname.yourmethodname();

Use this code for your Save.

try{
    String str="INSERT INTO tablename (column1,column2) VALUES(?,?)";
    pst=conn.prepareStatement(str);
    pst.setString(1, Description.getText());
    pst.setString(2, type.getText());
    pst.execute();
    JOptionPane.showMessageDialog(null,"Successfully Added!");
}catch (Exception e){
    JOptionPane.showMessageDialog(this, e.getMessage());
}

 Use this code for your Update.

try{
    String id = lblid.getText();
    String desc = Description.getText();
    String typ = type.getText();

    String str="UPDATE tablename SET Column1='" + desc + "',Column1='" + typ + "' WHERE columnid='" + id + "'";
    pst=conn.prepareStatement(str);
    pst.execute();
    JOptionPane.showMessageDialog(null,"Successfully Updated!");
}catch (Exception e){
    JOptionPane.showMessageDialog(this, e.getMessage());
}

 Use this code for your Delete.

try{
    int p = JOptionPane.showConfirmDialog(null, "Are you sure you want to delete this item?","Delete",JOptionPane.YES_NO_OPTION);
    if (p==0){                 
        String id = lblid.getText();
        String sql3="DELETE FROM tablename WHERE columnid='" + id + "'";
        pst=conn.prepareStatement(sql3);
        pst.execute();
        JOptionPane.showMessageDialog(null,"Successfully Deleted!");
    }
}catch (Exception e){
    JOptionPane.showMessageDialog(this, e.getMessage());
}

 

Leave a Reply

Be the First to Comment!

Notify of
avatar
wpDiscuz