ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

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

Updated on October 16, 2019
dwachira profile image

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

Lesson 50: How to create a database connection in Java NetBeans

Over the previous lesson, we looked at how we can use Structured Query Language (SQL) commands in a Java DB table. We were able to use SELECTFROM SQL commands and WHERE SQL clause to select required records.

Having done bit of SQL, you will now be able to appreciate the usefulness of these SQL commands when connecting to a database in Java NetBeans. First, we’ll learn how create a successful database connection and how to extract records from a database table to display them on the console.

Source

Later, we’ll learn how to connect Java form to a database table and populate it with records from a table using Java code.

We’ll also learn how to navigate through records in Java form using Java codes and command buttons for Next, Previous etc. We’ll also learn how to code for Update and Save command buttons.

For this lesson, we need to create a new project so, on the Java menu bar, click File and select New Project. I have called the project database_connect and class Database_Connect but you can call yours any preferred names. Notice that I have deleted all the default comments in the class.

Creating new Project and Class in Java NetBeans

How to create a database connection in Java NetBeans

To be able to connect to a database in Java NetBeans, we need a Connection object. The function of a Connection object is literally to create a connection to the database.

Access rights in form of Password and Username are required when connecting to a database and this is handled by the Driver Manager which also directs the connection to the database.

A safe connection to the database is the one where we anticipate occurrence of connection errors (Exceptions) and plan how to handle them so, in the connection code we’ll also include SQLException for handling Exceptions. Now, all together, add the following import statements at the top of the class.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

Having included these import statements, we’ll now setup a connection to the database. The statement to setup a connection to the database is as follow:

Connection conn = DriverManager.getConnection( host, username, password ); //Type as a single line

From the above statement, we are using the getConnection() method of the DriverManager. The getConnection() requires the database host name which is actually the location of the database and it also requires database username and password. If the database connection is successful, we’ll store the connection object in the String variable conn.

Checking on the School database we created in Lesson 48 you should be able to get the following host name:

jdbc:derby://localhost:1527/School

From the host name above, jdbc:derby is the database type, localhost, is the server being used, 1527 is the port number and School is the database name. We represent all these host name information using a String variable as follow:

String host = "jdbc:derby://localhost:1527/School";

We also need two more String variables to hold username and password. Remember, when we created the School database in Lesson 48, we specified username as admin and password as admin. These two will be stored in two separate String variables as follow:

String dName = "admin";
String dPass= "admin";

The String variables and connection will be placed in the main method of class Database_Connect as shown below.

How to connect to Database in Java NetBeans

package database_connect;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Database_Connect {

    public static void main(String[] args) {
   
        String host = "jdbc:derby://localhost:1527/School";
        String dName = "admin";
        String dPass= "admin";
        Connection conn = DriverManager.getConnection( host, dName, dPass );
  }
}

We have not yet included code to handle Exceptions i.e. SQLException error, that explains the appearance of the red wavy underline that you will get on the connection statement. We need to include code to handle potential connection errors which can result due to incorrect parameters such as incorrect host address.

If DriverManager attempt to connect to the database and fails, it will throw SQLException error. The Exception code in try … catch block should be able to catch and handle these errors. The code now will look as shown below when the try … catch block is included.

How to connect to Database in Java NetBeans

package database_connect;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Database_Connect {

    public static void main(String[] args) {
    try{
        String host = "jdbc:derby://localhost:1527/School";
        String dName = "admin";
        String dPass= "admin";
        Connection conn = DriverManager.getConnection( host, dName, dPass );
    }
   catch ( SQLException err ) {
        System.out.println( err.getMessage( ) );
    }
  }
}

Try running the code now but you might get the following error:

"java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused: connect."

This error is generated if the server is not on and running. If you get the above error, solve it by starting the server. On the Services tab, right click on Java DB and select Start Server. If the error still occurs, check your Firewall settings, the Firewall could be blocking the connection.

If the Server is on and running, you should see the following in the output window:

Date_Time : Security manager installed using the Basic server security policy.

Date_Time : Apache Derby Network Server - 10.8.1.2 - (1095077) started and ready to accept connections on port 1527

Server is now ready for connection, but running the program again will certainly generate another different error:

No suitable driver found for jdbc:derby://localhost:1527/School

The above error is generated because DriverManager is missing a driver to complete the connection to the database. There are different types of drivers such as Client Drivers and Embedded Drivers that we can use for connection purposes. In Java NetBeans, we can import one of such drivers. To import a driver, Click on Projects tab to locate your project, right click on its Libraries and select Add JAR/Forlder.

How to add database Driver Manager Java NetBeans

Clicking on Add JAR/Forlder will bring on a dialog box. What we need to do is to add derby Client Drivers to our project in form of a Java Archive file.

We need to locate the folder containing derby Client Drivers in the computer, preferably on Java installation path.

On a computer running on Windows, the location path can be: C:\Program Files\Sun\JavaDB\lib or C:\Program Files\Java\jdk1.7.0\db\lib. We are looking for a file called derbyclient.jar so if you are working on different operating system other than Windows you need to locate this file and note its path.

Once you get this file, double click on it and it will be added among the files in the Project Libraries.

Run the program again and this time you should be able to create a successful database connection without any error, you will not see any records but the program should display: BUILD SUCCESSFUL. Now that we have managed to create a successful connection to the database, we’ll move to the next task and that is extracting records from the Students table and displaying them on the console. We’ll do this in the next lesson.

<< Lesson 49 | Lesson 51 >>

Comments

    0 of 8192 characters used
    Post Comment
    • dwachira profile imageAUTHOR

      Danson Wachira 

      6 years ago from Nairobi, Kenya

      Hi RubieBautistaRoll, you don't have to download. derbyclient.jar come installed in your computer. Just look for it and add it to your program.

    • RubieBautistaRoll profile image

      RubieBautistaRoll 

      6 years ago

      i cant run my program successfully on this topic, because of derbyclient.jar.... where can i download this kind of file? please help me guys. Thanks.

    • dwachira profile imageAUTHOR

      Danson Wachira 

      6 years ago from Nairobi, Kenya

      Hi teaches12345,

      Glad to see you here, always following. Thanks for the visit and comment.

    • teaches12345 profile image

      Dianna Mendez 

      6 years ago

      Always a great post and one helpful to those who seek Java information. You do know your stuff!

    • dwachira profile imageAUTHOR

      Danson Wachira 

      6 years ago from Nairobi, Kenya

      Hi kidscrafts,

      Thanks for the positive compliment, i appreciate the visit and comment.

    • kidscrafts profile image

      kidscrafts 

      6 years ago from Ottawa, Canada

      Great hub! It's nice that you illustrate with some screen pictures to help people understand better this difficult subject!

    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)