Home > DeveloperSection > Articles > Simple Registration Form using JAVA Swing - Step2 (Connecting GUI with MySQL Database using JDBC)

Simple Registration Form using JAVA Swing - Step2 (Connecting GUI with MySQL Database using JDBC)


Java Java  MYSQL  Swing 
Ratings:
6 Comment(s)
 24526  View(s)
Rate this:

 Simple Registration Form Using JAVA Swing - Step2 

(Connecting GUI with MySQL Database using JDBC)

  Previously we seen how to  create a simple registration form in swing : Simple Registration form using Java Swing - Step1

Introduction of MySQL:

MySQL is the world’s most popular Open Source Relational SQL database management system. MySQL is one of the best RDBMS being used for developing web-based software applications.

Database: A database is a separate application that stores a collection of data. Each database has one or more distinct APIs for creating, accessing, managing, searching and replicating the data it holds.

RDBMS: A Relational Database Management System (RDBMS) is a software that enables you to implement a database with tables, columns and indexes. Guarantees the Referential Integrity between rows of various tables. Updates the indexes automatically. Interprets an SQL query and combines information from various tables.

 Definitions Related to Database:

Database: A database is a collection of tables, with related data.

Table: A table is a matrix with data. A table in a database looks like a simple spreadsheet.

Column: One column (data element) contains data of one and the same kind, for example

        the column postcode.

Row: A row (= tuple, entry or record) is a group of related data, for example the data of one 

        subscription.

Redundancy: Storing data twice, redundantly to make the system faster.

Primary Key: A primary key is unique. A key value can’t occur twice in one table. With a key, you can find at most one    row.

Foreign Key: A foreign key is the linking pin between two tables.

Compound Key: A compound key (composite key) is a key that consists of multiple columns, because one column is not sufficiently unique.

Index: An index in a database resembles an index at the back of a book.

Referential Integrity: Referential Integrity makes sure that a foreign key value always points to an existing row. 

 In this Registration Form we will use some other packages, packages are:

javax.swing.table.DefaultTableModel; DefaultTableModel returns a column class of Object. This is an implementation of TableModel that uses a Vector of Vectors to store the cell value objects.

java.sql.Connection;  A connection (session) with a specific database. SQL statements are executed and results are returned within the context of a connection. A Connection object's database is able to provide information describing its tables.

java.sql.PreparedStatement; A SQL statement is precompiled and stored in a PreparedStatement object. This object can then be used to efficiently execute this statement multiple times.

java.sql.ResultSet;  A table of data representing a database result set, which is usually generated by executing a statement that queries the database. A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set.

java.sql.Statement; The object used for executing a static SQL statement and returning the results it produces. By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All execution methods in the Statement interface implicitly close a statment's current ResultSet object if an open one exists.

java.awt.event; Provides interfaces and classes for dealing with different types of events fired by AWT components.

java.awt.Toolkit; This class is the abstract superclass of all actual implementations of the Abstract Window Toolkit. Subclasses of the Toolkit class are used to bind the various components to particular native toolkit implementations.

java.awt.Dimension; The Dimension class encapsulates the width and height of a component (in integer precision) in a single object. The class is associated with certain properties of components. Several methods defined by the Component class and the LayoutManager interface return a Dimension object.

For connecting java application with the MySQL database, you need to follow steps to perform database connectivity:

 ( In this example we are using MySQL as the database. So we need to know following informations for the MySQL database ):


Driver class:  The driver class for the mysql database is com.mysql.jdbc.Driver.

Connection URL:  The connection URL for the mysql database is  jdbc:mysql://localhost:3306/project where jdbc is the API, mysql is the database, localhost is the server name on which mysql is running, we may also use IP address, 3306 is the port number and project is the database name. We may use any database, in such case, you need to replace the project with your database name.

Username:  The default username for the mysql database is root.

* Password:  Password is given by the user at the time of installing the mysql database. In this example, we are going to use  root as the password.

 [ To connect java application with the MySQL database mysqlconnector.jar file is required to be loaded.]

Java Codes:

RegistrationFormGUI.java

import java.awt.Color;

import java.awt.Dimension;

import java.awt.GridLayout;

import java.awt.Toolkit;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement; import java.sql.Statement;

import javax.swing.BorderFactory;

import javax.swing.ButtonGroup;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

import javax.swing.JRadioButton;

import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField;

import javax.swing.table.DefaultTableModel;

@SuppressWarnings("serial")

public class RegistrationFormGUI extends JFrame{  

      Connection con;       Statement stmt;      PreparedStatement preStatement,updatePreStmt;

      JLabel title, idLabel, nameLabel, genderLabel, addressLabel, contactLabel;

      JTextField idField, nameField, genderField, addressField, contactField;

      JButton registerButton, exitButton,updateButton,deleteButton,resetButton,

refresh;

      JRadioButton male, female;       ButtonGroup bg;

      JPanel panel;       JTable table;       DefaultTableModel model;

      JScrollPane scrollpane;       public RegistrationFormGUI() {            // TODO Auto-generated constructor stub

           super("REGISTRATION FORM");             setSize(770, 420);             setLayout(null);

            // Calling connect method, this will connect us to database             connect();

         // Defining Labels

            title = new JLabel("Registration Form");

            title.setBounds(60, 7, 200, 30);

            idLabel = new JLabel("ID");

            idLabel.setBounds(30, 50, 60, 30);

            nameLabel = new JLabel("Name");

            nameLabel.setBounds(30, 85, 60, 30);

            genderLabel = new JLabel("Gender");

            genderLabel.setBounds(30, 120, 60, 30);

            addressLabel = new JLabel("Address");

            addressLabel.setBounds(30, 155, 60, 30);

            contactLabel = new JLabel("Contact");

            contactLabel.setBounds(30, 190, 60, 30);

            // Defining ID field             idField = new JTextField();

            idField.setBounds(95, 50, 130, 30);             idField.setEnabled(false);

            // Defining Name field             nameField = new JTextField();

            nameField.setBounds(95, 85, 130, 30);        

            // Defining Gender Buttons             male = new JRadioButton("Male");

            male.setBounds(95, 120, 60, 30);

            female = new JRadioButton("Female");

            female.setBounds(155, 120, 70, 30);           

            bg = new ButtonGroup();

            bg.add(male);

            bg.add(female);

            addressField = new JTextField();

            addressField.setBounds(95, 155, 130, 30);

            contactField = new JTextField();

            contactField.setBounds(95, 190, 130, 30);

 

            // fixing all Label,TextField,RadioButton

            add(title);

            add(idLabel);

            add(nameLabel);

            add(genderLabel);

            add(addressLabel);

            add(contactLabel);

            add(idField);

            add(nameField);

            add(male);

            add(female);

            add(addressField);

            add(contactField);

            // Defining Exit Button

            exitButton = new JButton("Exit");

            exitButton.setBounds(25, 250, 80, 25);           

            // Defining Register Button

            registerButton = new JButton("Register");

            registerButton.setBounds(110, 250, 100, 25);

            // Defining Update Button

            updateButton = new JButton("Update");

            updateButton.setBounds(110, 285, 100, 25);

            updateButton.setEnabled(false);

            // Defining Delete Button

            deleteButton = new JButton("Delete");

            deleteButton.setBounds(25, 285, 80, 25);

            deleteButton.setEnabled(false);

            // Defining Reset Button

            resetButton = new JButton("Reset");

            resetButton.setBounds(60, 320, 100, 25);

            resetButton.setEnabled(false);

            // fixing all Buttons

            add(exitButton);

            add(registerButton);

            add(updateButton);

            add(deleteButton);

            add(resetButton);   

            // Defining Panel

            panel = new JPanel();

            panel.setLayout(new GridLayout());

            panel.setBounds(250, 20, 480, 330);

            panel.setBorder(BorderFactory.createDashedBorder(Color.blue));

            add(panel);

            // Defining Refresh Button

            refresh = new JButton("Refresh Table");

            refresh.setBounds(350, 350, 270, 15);

            add(refresh);

            //Defining Model for table

            model = new DefaultTableModel();             //Adding object of DefaultTableModel into JTable

            table = new JTable(model);

            //Fixing Columns move

            table.getTableHeader().setReorderingAllowed(false);

            // Defining Column Names on model

model.addColumn("S.No");

model.addColumn("ID");

model.addColumn("Name");

model.addColumn("Gender");

model.addColumn("Address"); model.addColumn("Contact");

 

            // Enable Scrolling on table

           scrollpane = new JScrollPane(table,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,

JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

            panel.add(scrollpane);

            //Displaying Frame in Center of the Screen

            Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();

            this.setLocation(dim.width/2-this.getSize().width/2,

dim.height/2-this.getSize().height/2);

            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            setResizable(false);

            setVisible(true);

      }

      // Connection with Database

      public void connect(){

            try{

                  Class.forName("com.mysql.jdbc.Driver");

                  con =DriverManager.getConnection(

"jdbc:mysql://localhost:3306/test","root","1234");

                  stmt = con.createStatement();

                  preStatement = con.prepareStatement("insert into regForm(

name,gender,address,contact) values(?,?,?,?)");

            }catch(Exception e){

     System.out.print(e.getMessage());

   }

      }

}

 

DynamicRegForm Class – DynamicRegForm.java

import javax.swing.*;

import javax.swing.table.DefaultTableModel;

import java.awt.event.*;

import java.sql.ResultSet;

@SuppressWarnings("serial")

public class DynamicRegForm extends RegistrationFormGUI{

      String gender = "";

      ResultSet rst,rstLast;

      Object[][] data;

      int serialNo;

      String SHOW = "Show";

      RegistrationFormGUI formGUIObject;

      // Defining Constructor

      DynamicRegForm(){

            nameField.addKeyListener(new KeyAdapter() {

                  public void keyTyped(KeyEvent e) {

                  if(nameField.getText().length()>=15)

                        e.consume();

                  }

            });

            male.addActionListener(new ActionListener() {

                  public void actionPerformed(ActionEvent e) {

                        gender = "Male";

                  }             });

            female.addActionListener(new ActionListener() {

                  public void actionPerformed(ActionEvent e) {

                        gender = "Female";

                  }

            });

            addressField.addKeyListener(new KeyAdapter() {

                  public void keyTyped(KeyEvent e) {

                  if(addressField.getText().length()>50)

                        e.consume();

                  }

            });

            contactField.addKeyListener(new KeyAdapter() {

                  public void keyTyped(KeyEvent e) {

                        char c = e.getKeyChar();

                        if (!((c >= '0') && (c <= '9') ||

(c == KeyEvent.VK_BACK_SPACE) ||

(c == KeyEvent.VK_DELETE))) {

                              // getToolkit().beep();

                              e.consume();

                        }

                        if(contactField.getText().length()>9)

                              e.consume();

                  }

            });

            exitButton.addActionListener(new ActionListener(){

                  public void actionPerformed(ActionEvent arg0) {

                        try{

                              con.close();

                              System.exit(0);

                        }catch(Exception ex){

System.out.println(ex.getMessage());

}

                  }

            });

            registerButton.addActionListener(new AbstractAction(SHOW){

                   public void actionPerformed(ActionEvent ae){

                         try{

                            if (ae.getSource() == registerButton) {

                              if (nameField.getText().equals(""))

                                   JOptionPane.showMessageDialog(idField,

"Please provide Name_Field");

                                else if(addressField.getText().equals(""))

                                   JOptionPane.showMessageDialog(idField,

"Please provide Address_Field");

                                else if(contactField.getText().equals(""))                                    JOptionPane.showMessageDialog(idField, "Please provide Contact_Field");

                                else if(gender.equals(""))

                                 JOptionPane.showMessageDialog(idField, "Please select Gender");

                                else {

                               //Fetching column values from Database

                               preStatement.setString(1,nameField.getText());

                                 preStatement.setString(2,gender);

                                 preStatement.setString(3,addressField.getText());

                                 preStatement.setString(4,contactField.getText());

                               //Executing MySQL Update Query

                                int i = preStatement.executeUpdate();

                                 if(i==1){

                                  JOptionPane.showMessageDialog(panel,

"Successfully Registered");

                    }

 

                                 // showing last row

                               rstLast = stmt.executeQuery("select *from regForm");

                                rstLast.last();

                                String string = serialNo++ +",

"+String.valueOf(rstLast.getLong(1))+",

"+rstLast.getString(2)+",

"+rstLast.getString(3)+",

"+rstLast.getString(4)+",

"+rstLast.getString(5);

                                 Object[] row = null;

                                row = string.split(",");

                                 model.addRow(row);

                                 panel.revalidate();

 

                                 // fields are blank

                                 blankFields();

                               }

                              }

                       }catch(Exception ex){

System.out.println(ex.getMessage());

}

                   }

            });

 

            updateButton.addActionListener(new AbstractAction(SHOW){

              public void actionPerformed(ActionEvent e){

                  if (nameField.getText().equals(""))

                        JOptionPane.showMessageDialog(idField,

"Please provide Name_Field");

                  else if(addressField.getText().equals(""))

                        JOptionPane.showMessageDialog(idField,

"Please provide Address_Field");

                  else if(contactField.getText().equals(""))

                        JOptionPane.showMessageDialog(idField,

"Please provide Contact_Field");             

                  else if(gender.equals(""))

                        JOptionPane.showMessageDialog(idField,

"Please select Gender");                 

                  else {

                              int r = table.getSelectedRow();

                              try{

                              if(r>=0){

                                if(male.isSelected())

                                   gender = male.getText();                                  else                                     gender = female.getText();

                                    String id = (String)table.getModel().

getValueAt(r,1);

                                    updatePreStmt = con.prepareStatement(

"update regForm set name=?,

gender=?,address=?,contact=?

where id="+id);

                                 updatePreStmt.setString(1,nameField.getText());

                                  updatePreStmt.setString(2,gender);

                                  updatePreStmt.setString(3,addressField.getText());

                                  updatePreStmt.setString(4,contactField.getText());

                                  int i = updatePreStmt.executeUpdate();

                                  if(i==1){

                                     table.setValueAt(nameField.getText(),r,2);

                                     table.setValueAt(gender, r, 3);

                                     table.setValueAt(addressField.getText(),r,4);

                                     table.setValueAt(contactField.getText(), r, 5);

                                  }

                                  else JOptionPane.showMessageDialog(panel,

"ID does't Exists in Database");

                              }

}catch(Exception ex){

System.out.println("Update section: "+

ex.getMessage());

}

                        }

              }

          });

 

            //Registering Anonymous Listener Class

            deleteButton.addActionListener(new AbstractAction(SHOW){

              public void actionPerformed(ActionEvent e){

                  try{

                  //Getting Selected Row No

                  int r = table.getSelectedRow();

                  if(r>=0){

                        if (JOptionPane.showConfirmDialog(panel,

"Are you sure want to Delete this 'RECORD' ?","WARNING",

JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION){

                              String id = (String)table.getModel().getValueAt(r,1);

 

                              // Executing MySQL Update Command

                              int i = stmt.executeUpdate("delete from regForm

where id="+id);

                              if(i==1){

                                    model.removeRow(r);

 

                                    // fields are blank

                                    blankFields();

                                    registerButton.setEnabled(true);

                                    deleteButton.setEnabled(false);

                                    updateButton.setEnabled(false);

                              }

                        }

                  }

}catch(Exception ex){

System.out.println(ex.getMessage());

}

              }

          });

 

           //Registering Anonymous Listener Class

            resetButton.addActionListener(new ActionListener(){

                  public void actionPerformed(ActionEvent arg0) {

                        // calling method resetFields()

                        resetFields();

                        registerButton.setEnabled(true);

                        updateButton.setEnabled(false);

                        deleteButton.setEnabled(false);

                        resetButton.setEnabled(false);

                  }

            });

            // Registering Anonymous Listener Class

            refresh.addActionListener(new ActionListener() {

                  public void actionPerformed(ActionEvent arg0) {

                        //calling refresh() method

                        refreshTable();

                  }

            });

            //Registering Anonymous Listener Class

            table.addMouseListener(new MouseListener(){

                  public void mouseClicked(MouseEvent arg0){

                        //Getting Selected Row No

                  int r = table.getSelectedRow();

                  if(r>=0){

                        deleteButton.setEnabled(true);

                        updateButton.setEnabled(true);

                        resetButton.setEnabled(true);

                        registerButton.setEnabled(false);

                        //Fetching records from Table on Fields

                        idField.setText(""+table.getModel().getValueAt(r,1));

                        nameField.setText(""+table.getModel().getValueAt(r,2));

                        if(table.getModel().getValueAt(r,3).equals("Male"))

                              male.setSelected(true);

                        else

                              female.setSelected(true);

                        addressField.setText(""+table.getModel().getValueAt(r,4));

                        contactField.setText(""+table.getModel().getValueAt(r,5));

                  }

                  }

//                @Override

                  public void mouseReleased(MouseEvent arg0) {}

//                @Override

                  public void mousePressed(MouseEvent arg0) {}

//                @Override

                  public void mouseExited(MouseEvent arg0) {}

//                @Override

                  public void mouseEntered(MouseEvent arg0) {}

            });

            // Displaying rows into the Frame table

            addRows();

      }

      // addRows method

      private void addRows(){

            try{

            Object[] row = null;

            //Generating Serial No

            serialNo=1;

            rst = stmt.executeQuery("select *from regForm");

            while(rst.next()){

                  String string = serialNo++ +","+String.valueOf(rst.getLong(1))+",

"+rst.getString(2)+","+rst.getString(3)+",

"+rst.getString(4)+","+rst.getString(5);

                  row = string.split(",");

                  // Adding records in table model

                  model.addRow(row);

            }

            panel.revalidate();

            }catch(Exception ex){ System.out.println(ex.getMessage()); }

      }

      private void resetFields(){

 

            //calling method blankfields()

            blankFields();

      }

 

      // refresh method

      private void refreshTable(){

 

            // removing all the rows of the table

            DefaultTableModel dm = (DefaultTableModel)table.getModel();

            dm.getDataVector().removeAllElements();

            System.out.println("Refresh Table");

            //calling method addRows

            addRows();

      }

      private void blankFields(){

            // fields will be blank

            idField.setText("");

            nameField.setText("");

            gender = "";

            bg.clearSelection();

            addressField.setText("");

            contactField.setText("");

      }

      // main() method

      public static void main(String[] args) {

            new DynamicRegForm();

      }     }

 

 

Running the Application

 

 

Next, we will learn about : Creating Dynamic Objective Test Application through Swing in JAVA ( Using MySQL Database )


null

By Xavier Prince on   8 months ago
Why it always shows "null" everytime i click a button?

the program is not working

By Tejas Rane on   8 months ago
it shows the error that define the main method in the program i have tried in different ways but its not working give me a solution plzz......

null solution

By Tarun Kumar on   7 months ago
I think the null problem is coming because the database table format is not matching. remember one thing my table name is 'regform'. Now, use below script to create table in your mysql database:
CREATE TABLE IF NOT EXISTS `regform` (
  `id` double NOT NULL AUTO_INCREMENT,
  `name` text NOT NULL,
  `gender` text NOT NULL,
  `address` text NOT NULL,
  `contact` text NOT NULL,
  PRIMARY KEY (`id`)
);
and after you can set a default value for auto_increment, script is here:
alter table regform auto_increment = 1000;
(default value for auto_increment script is not mandatory)
that's it!

Add MySql Connector to project built path

By Sagarsingh Jadhav on   7 months ago
Even I was facing the same issue. Getting null at the point when I execute the program. It was because the java was not able to read the driver from Class.forName();  Adding "mysql-connector-java-5.1.25-bin.jar" to project build path resolved the problem.


form is not opening

By kapeesh gupta on   3 months ago
 Dear,

 I have written this code but code is not running. Fetching error something like this:

 Exception in thread "main" java.lang.NullPointerException
at xyz.Xyz.<init>(Xyx.java:59)
at xyz.Abc.<init>(Abc.java:20)
at xyz.Abc.main(Abc.java:105)

Please give me solution asap.

Thanks


null

By Nayan Pal on   3 months ago
facing null problem.

Don't want to miss updates? Please click the below button!

Follow MindStick