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 SELECT … FROM 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.
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.
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:
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
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
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.
Other related Hubs ...
- How to use Java Save File dialog box to save files
Java Save dialog box, unlike Java Open dialog box, is used to display various computer locations where users can save files. This article discusses how to implement Java Save dialog box in Java NetBeans programming environment.
- How to read a text file in Java NetBeans
Text files have many uses in programming such as storing program passwords, presenting program documentation to users or just holding important information, for example, table structures and file formats.
- How to use Java Open File dialog box to open files
Using Java Open dialog box is one of the easiest ways of accessing computer files such as text files for manipulation. This article discusses how to implement Open dialog box in Java NetBeans for opening text files.
- Arrays of string type in Java
In some cases in Java programming, you would need to store values of string type in an array like days of the week or Boolean (True or False) values. In this article, we shall learn how we can implement and work with arrays of string type in Java.
Want to make money online?
Danson Wachira (author) from Nairobi, Kenya on July 07, 2013:
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 on July 02, 2013:
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.
Danson Wachira (author) from Nairobi, Kenya on April 26, 2013:
Glad to see you here, always following. Thanks for the visit and comment.
Dianna Mendez on April 26, 2013:
Always a great post and one helpful to those who seek Java information. You do know your stuff!
Danson Wachira (author) from Nairobi, Kenya on April 16, 2013:
Thanks for the positive compliment, i appreciate the visit and comment.
kidscrafts from Ottawa, Canada on April 13, 2013:
Great hub! It's nice that you illustrate with some screen pictures to help people understand better this difficult subject!