Skip to main content
Updated date:

Programming in Java Netbeans - A Step by Step Tutorial for Beginners: Lesson 52

Danson Wachira is a certified Trainer in Computer Science, Information Technology and related studies.

Table of Contents

<< Lesson 51 | Lesson 53 >>

Lesson 52: How to connect Java forms to database in Java NetBeans

Over the previous lesson, we were able to access a database table to extract and display records on Java NetBeans console window. We also learnt about the usefulness of SQL statement, ResultSet, record Cursor and how to navigate through ResultSet using Cursor movement methods.

Typical in many database applications (desktop applications and mobile apps) are forms that are used as GUI (Graphical User Interface) to display data to users. Database applications usually connect to a backend RDBMS (Relational Database Management System) such as Microsoft Access, Oracle, MySQL, SQL Server etc. to access data and display it on forms for data manipulation.

Sample - Database Oriented Application

programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-52

In this lesson, we’ll learn how to connect a Java form to a database table to extract records and populate the form with table records. We’ll first create the user interface (Form, Textfields, command buttons etc.) after which we shall connect the form to a database table.

Up to this point you should be able to create the user interface on your own. If you would like to refer on previous lessons about how to create a user interface in Java NetBeans, feel free to do so. You can find valuable information on how to create a user interface in Java NetBeans here. Start by creating a new form in database_connect package.

programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-52

The interface we shall create should accommodate all the fields from the table we created earlier in Lesson 48 although it's not a must that you include all fields. After you have created the interface, it should look similar to the following form when run.

programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-52

Now that we have the user interface, we want to connect it to the Students database table so that the first record from the table will populate the text fields on the form.

Notice that we have also added navigation buttons to navigate to First, Previous, Next, Last record and data manipulation buttons to Delete record, add New record and Save record.

To begin, click on the Source part of the form to reveal form codes. Add the following import statements at the top of class (form code) just like we did before.

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.Statement;

import java.sql.ResultSet;

import javax.swing.JOptionPane;

programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-52

Don’t worry about the underlines on the import statements, they just denotes that the import objects are yet to be used. Beware though if the underlines are red in color. Red underline shows an error.

Add the following variables inside the class, these are becoming all too familiar now.

Connection conn;
Statement state;
ResultSet Rset;

Add the following method after the class constructor:

public void DoConnect( ) {

}

Then create a constructor for the above method and place it under the form constructor just below initComponents().

The constructor, if you can remember from Lesson 28, should have the same name and structure as the method so, it should be as follow.

DoConnect();

The code now should look as shown below:

programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-52

From the above code, we have setup a connection named conn, a statement object named state and ResultSet called Rset. You have already met these in previous lessons. The DoConnect() method will be called when the form loads. It is in this method that we’ll place the code to connect to the database table and to populate form textfields with data. The code now should look as shown below.

Code sample: How to connect Java form to database table

package database_connect;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
public class StudForm extends javax.swing.JFrame {
        Connection conn;
        Statement state;
        ResultSet Rset;

    public StudForm() {
        initComponents();
        DoConnect();
    }
    public void DoConnect( ) {
       try{
        String host = "jdbc:derby://localhost:1527/School";
        String dName = "admin";
        String dPass = "admin";
        Connection conn = DriverManager.getConnection( host, dName, dPass ); //Connect to database and extract records
        Statement state = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
        String SQL = "SELECT * FROM APP.Students";
        ResultSet Rset = state.executeQuery( SQL );
       
        Rset.next( );
        int Id = Rset.getInt("StdID");
        String Id2 = Integer.toString(Id); //Convert int ID to String
        String sName = Rset.getString("StdName");
        String sFaculty = Rset.getString("Faculty");
        String sCourse = Rset.getString("Course");
        String sCity = Rset.getString("City");
        String sAddress = Rset.getString("Address");
        String sTelephone = Rset.getString("Telephone");
        String sRemarks = Rset.getString("Remarks");
        
        txtID.setText(Id2); //Set record values onto form textfields
        txtName.setText(sName);
        txtFaculty.setText(sFaculty);
        txtCourse.setText(sCourse);
        txtCity.setText(sCity);
        txtAddress.setText(sAddress);
        txtTelephone.setText(sTelephone);
        txtRem.setText(sRemarks);
        }
   catch ( SQLException err ) { //Handle database connection errors
        System.out.println( err.getMessage( ) );
  }
}

Much of the code above should be familiar to you from the previous lesson. What is new to you is the last bit where we are taking the record values and setting them as text for the textfields on the form. Notice that we have changed Id from int to String type since a textfield only accepts Strings. Run the form now and you should be able to display the first record on the form. Don’t forget to start the Java DB Server though to avoid database connection errors.

Database table with records

programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-52

Database table connected to Java form

programming-in-java-netbeans-a-step-by-step-tutorial-for-beginners-lesson-52

You have now connected a Java form to a database table. As you can see, it is fairly simple and the steps are straight forward. All database applications are based on such database connections and having known how to connect a form to a database is a great accomplishment in programming. In the next lesson, we shall learn how to code for record navigation command buttons.

<< Lesson 51 | Lesson 53 >>

  • How to implement Inheritance in Java NetBeans
    Inheritance is one of the difficult concepts to grasp in Object Oriented Programming. Java programming language provide inheritance where child classes can inherit their parent class. This article illustrates how to implement inheritance in Java.
  • How to implement User Defined Methods in Java NetBeans
    Having programming ability to create User Defined Methods (UDMs) is one of the most sought skills in programming and software development. This article discusses how to create user defined methods in Java programming language.
  • How to implement Multi-dimensional Arrays in Java NetBeans
    Multi-dimensional arrays can be implemented in Java programming language by specifying the number of rows and columns in array declaration. This article discusses how to implement multi-dimensional arrays in Java NetBeans.
  • Control Structures in Java - The Switch Statement
    In this lesson we shall learn how to use the Switch statement in Java programming. Switch statement is a selection statement, that means when used, it select one value among many values.

Comments

Danson Wachira (author) from Nairobi, Kenya on May 18, 2013:

Hi teaches12345,

It takes time to come up with one but i like it because i know they are helping a student somewhere. Thanks for stopping here and commenting.

Dianna Mendez on May 17, 2013:

Just stopping in for the support. As always, a great detailed article useful to those who need the advice and help.

Danson Wachira (author) from Nairobi, Kenya on April 26, 2013:

Hi malique,

Avoid being drowned :-) Thanks for the visit and comment.

malique on April 26, 2013:

thx man..u save my life..from drowning

brad pitt on April 22, 2013:

thx man...

Danson Wachira (author) from Nairobi, Kenya on April 20, 2013:

Hi Iddi,

Now you got it, glad that it was helpful. Thanks for the visit and comment.

Iddi on April 20, 2013:

You are awesome man, just when i was about to give up hope about searching this topic, i got this tutorial!! Very well explained and now i can continue from where i was stuck. Thanks and God bless.

Danson Wachira (author) from Nairobi, Kenya on April 18, 2013:

Hi kidscrafts,

You have a point, visual add more information. Am not yet there but i try as much as i can to add visual in these tutorials. Thanks for the visit and comment.

kidscrafts from Ottawa, Canada on April 18, 2013:

Another great lesson on Java NetBeans, Dwachira!

Being a visual person myself, I find that great that you put pictures of some screens and also the code! I am sure that it's helping a lot of people who try to master this!

Related Articles