Java MySQL Database - JComboBox - INSERT SELECT UPDATE DELETE Full

October 30, 2017 Oclemy Java MySQL, Java JComboBox 6 minutes, 27 seconds

This is an Java MySQL example .Its a simple CRUD app.We shall save items to MySQL,retrieve,update and delete.We shall be using JTextfields,JButtons and JComboBox.We used netbeans in this tutorial.

What we do :

  • Connect to MySQL using JDBC.
  • User types data into JTextField and clicks save button.
  • We then save this data into MySQL.
  • We retrieve after saving and bind our data to jcombobox.
  • As user enters data he can see the changes he's made.
  • User can select an item from combobox.
  • It gets set to the corresponding jtextfield.
  • He can change and click update to update.
  • Or he can delete and it gets deleted from MySQL database.

SECTION 1 : Our Database Class

Database CRUD class

Main Responsibility : Perform all CRUD operations.

  • INSERTS/SAVES data to MySQL database.
  • SELECTS/RETRIEVES data to MySQL.
  • UPDATES/EDITS data.
  • DELETES data.

 

package ComboDataBase;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.DefaultComboBoxModel;

public class DBClass {

    String conString = "jdbc:mysql://localhost:3306/playersdb";
    String username = "root";
    String password = "";

    //INSERT INTO DB
    public Boolean add(String name) {
        //SQL STMT
        String sql = "INSERT INTO playerstb(Name) VALUES('" + name + "')";

        try {
            //CONNECTION"
            Connection con = DriverManager.getConnection(conString, username, password);

            //STATEMENT
            Statement s=con.prepareStatement(sql);

            //EXECUTE
            s.execute(sql);

            return true;

        } catch (SQLException ex) {
            ex.printStackTrace();
             return false;
        }

    }

    //RETRIEVE DATA
    public DefaultComboBoxModel retrieve()
    {
        DefaultComboBoxModel dm=new DefaultComboBoxModel();

        //SQL
        String sql="SELECT Name FROM playerstb";

        try
        {
            Connection con=DriverManager.getConnection(conString, username, password);

            //STATEMENT
            Statement s=con.prepareStatement(sql);
            ResultSet rs=s.executeQuery(sql);

            //LOOP THRU GETTING ALL VALUES
            while(rs.next())
            {
                //GET VALUES
                String name=rs.getString(1);

                dm.addElement(name);
            }

            return dm;

        }catch (SQLException ex) {
            ex.printStackTrace();
             return null;
        }

    }

    //UPDATE DATA
    public Boolean update(String id,String value)
    {
        String sql="UPDATE playerstb SET Name ='" + value + "' WHERE Name='" + id + "'";

        try
        {
            //GET COONECTION
            Connection con=DriverManager.getConnection(conString, username, password);

            //STATEMENT
            Statement s=con.prepareStatement(sql);

            //EXECUTE
            s.execute(sql);

            return true;

        }catch (SQLException ex) {
            ex.printStackTrace();
             return false;
        }

    }

    //DELETE
    public Boolean delete(String id)
    {
        String sql="DELETE FROM playerstb WHERE Name ='"+id+"'";

        try
        {
            //GET COONECTION
            Connection con=DriverManager.getConnection(conString, username, password);

             //STATEMENT
            Statement s=con.prepareStatement(sql);

            //EXECUTE
            s.execute(sql);

            return true;

        }catch (SQLException ex) {
            ex.printStackTrace();
             return false;
        }

    }
}

   

SECTION 2 : Our GUI Class

GUI and Main class

Main Responsibility : STARTS OUR APPLICATION

  • Is our main class.
  • Derives from JFrame.
  • Handles all GUI interactions such as input of data.
  • Instantiates Database class and invokes its database manipulation methods.

 

package ComboDataBase;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.UIManager;

public class GUI_Class extends javax.swing.JFrame {

  String id="";

    public GUI_Class() {
        initComponents();
    }

   private void retrieve()
   {
       DefaultComboBoxModel dm=new DBClass().retrieve();
       jComboBox1.setModel(dm);
   }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLabel2 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jComboBox1 = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        nameTxt = new javax.swing.JTextField();
        addBtn = new javax.swing.JButton();
        retrieveBtn = new javax.swing.JButton();
        updateBtn = new javax.swing.JButton();
        deleteBtn = new javax.swing.JButton();
        clearBtn = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel2.setText("ProgrammingWizards Channel");

        jPanel1.setBackground(new java.awt.Color(45, 155, 193));

        jComboBox1.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jComboBox1ItemStateChanged(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(41, 41, 41)
                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(66, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(58, 58, 58)
                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(64, Short.MAX_VALUE))
        );

        jLabel1.setText("Name");

        addBtn.setText("Add");
        addBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addBtnActionPerformed(evt);
            }
        });

        retrieveBtn.setText("Retrieve");
        retrieveBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                retrieveBtnActionPerformed(evt);
            }
        });

        updateBtn.setText("Update");
        updateBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                updateBtnActionPerformed(evt);
            }
        });

        deleteBtn.setText("Delete");
        deleteBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteBtnActionPerformed(evt);
            }
        });

        clearBtn.setText("Clear");
        clearBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clearBtnActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(nameTxt))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(8, 8, 8)
                                .addComponent(addBtn)
                                .addGap(18, 18, 18)
                                .addComponent(retrieveBtn))
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(updateBtn)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(deleteBtn)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(clearBtn)
                .addGap(65, 65, 65))
            .addGroup(layout.createSequentialGroup()
                .addGap(115, 115, 115)
                .addComponent(jLabel2)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(31, 31, 31)
                .addComponent(jLabel2)
                .addGap(51, 51, 51)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(nameTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(58, 58, 58)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(addBtn)
                            .addComponent(retrieveBtn))
                        .addGap(28, 28, 28)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(updateBtn)
                            .addComponent(deleteBtn))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(clearBtn)
                .addContainerGap(18, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {
       id=jComboBox1.getSelectedItem().toString();
       nameTxt.setText(id);
    }

    private void addBtnActionPerformed(java.awt.event.ActionEvent evt) {
        if(new DBClass().add(nameTxt.getText()))
        {
            JOptionPane.showMessageDialog(null, "Successfully Inserted");
            retrieve();;

             //SELECT ADDED ITEM
            jComboBox1.setSelectedItem(nameTxt.getText());
            //CLEAR TXT
            nameTxt.setText("");
        }else
        {
            JOptionPane.showMessageDialog(null, "Not Inserted");
        }
    }

    private void retrieveBtnActionPerformed(java.awt.event.ActionEvent evt) {
      retrieve();
    }

    private void updateBtnActionPerformed(java.awt.event.ActionEvent evt) {
       if(new DBClass().update(id,nameTxt.getText()))
        {
            JOptionPane.showMessageDialog(null, "Successfully Updated");
            retrieve();;

             //SELECT ADDED ITEM
            jComboBox1.setSelectedItem(nameTxt.getText());
            //CLEAR TXT
            nameTxt.setText("");
        }else
        {
            JOptionPane.showMessageDialog(null, "Not Updated");
        }
    }

    private void deleteBtnActionPerformed(java.awt.event.ActionEvent evt) {
         if(new DBClass().delete(id))
        {
            JOptionPane.showMessageDialog(null, "Successfully Deleted");
            retrieve();;

            //CLEAR TXT
            nameTxt.setText("");
        }else
        {
            JOptionPane.showMessageDialog(null, "Not Deleted");
        }
    }

    private void clearBtnActionPerformed(java.awt.event.ActionEvent evt) {
        jComboBox1.setModel(new DefaultComboBoxModel());
    }

    public static void main(String args[]) {

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
//                 try {
//                    // select Look and Feel
//                    UIManager.setLookAndFeel("com.jtattoo.plaf.smart.SmartLookAndFeel");
//            // start application
//
//                } catch (Exception ex) {
//                    ex.printStackTrace();
//                }
                new GUI_Class().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton addBtn;
    private javax.swing.JButton clearBtn;
    private javax.swing.JButton deleteBtn;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField nameTxt;
    private javax.swing.JButton retrieveBtn;
    private javax.swing.JButton updateBtn;
    // End of variables declaration
}

LAST SECTION

  • Lets share more tips in OUR FB PAGE.
  • To see the XML  we were parsing and the website itself please have look at the tutorial at our youtbe channel : ProgramminWizards.
  • You'll also find the demo for this example and step by step explanations.

Comments