ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

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

Updated on October 23, 2019
dwachira profile image

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

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

Source

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.

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.

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;

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:

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

Database table connected to Java form

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 >>

Comments

    0 of 8192 characters used
    Post Comment
    • dwachira profile imageAUTHOR

      Danson Wachira 

      7 years ago from Nairobi, Kenya

      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.

    • teaches12345 profile image

      Dianna Mendez 

      7 years ago

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

    • dwachira profile imageAUTHOR

      Danson Wachira 

      7 years ago from Nairobi, Kenya

      Hi malique,

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

    • profile image

      malique 

      7 years ago

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

    • profile image

      brad pitt 

      8 years ago

      thx man...

    • dwachira profile imageAUTHOR

      Danson Wachira 

      8 years ago from Nairobi, Kenya

      Hi Iddi,

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

    • profile image

      Iddi 

      8 years ago

      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.

    • dwachira profile imageAUTHOR

      Danson Wachira 

      8 years ago from Nairobi, Kenya

      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 profile image

      kidscrafts 

      8 years ago from Ottawa, Canada

      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!

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://maven.io/company/pages/privacy

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
    ClickscoThis is a data management platform studying reader behavior (Privacy Policy)