Connecting To Oracle Database From NetBeans IDE
Connecting To Oracle Database From NetBeans IDE
NetBeans IDE includes built-in support for Oracle Database. You can easily establish a connection from inside the IDE
and begin working with the database. This tutorial demonstrates how to use a local installation of Oracle Database 10g
Express Edition (Oracle Database XE), a lightweight database that is free to develop, deploy, and distribute.
This document shows how to set up a connection to a local installation of Oracle Database XE from the NetBeans IDE,
use the IDE's built-in SQL editor to handle the database data, and how to enable the OCI 8 PHP extension to write PHP
code that connects to an Oracle database.
To follow this tutorial, you need the following software and resources.
Software or Resource
NetBeans IDE
Version Required
7.2, 7.3, 7.4, 8.0, Java EE bundle
10 g Express Edition
ojdbc6.jar
This tutorial demonstrates how to connect to an Oracle Database XE instance installed on your local system, but
the steps can also be applied when you are connecting to a remote instance. If you are connecting to a local
instance you need to download and install Oracle Database XE. The installation process is simple and intuitive,
but if you have questions, refer to the Oracle Database XE installation guide for your platform.
There are two categories of Oracle JDBC drivers: OCI and JDBC Thin.
o Oracle's JDBC Thin driver is based on Java and is platform independent. This standalone driver does not
require the presence of other Oracle libraries and allows a direct connection to an Oracle Database. This
tutorial uses this driver to show how to connect to Oracle Database. Before walking through the tutorial,
you need to download the ojdbc6.jar file and save it on your system.
Note for Windows users: Windows may change the extension of the downloaded file from .jar to .zip. It
is still a .jar file, however. You can rename the file to .jar.
o
Oracle's OCI driver uses Oracle's native client libraries to communicate with databases. These libraries
are obtained as part of the Oracle Instant Client. Although the Thin driver is sufficient in most cases, you
might also want to use the OCI driver by following the steps in Using OCI JDBC Driver with the NetBeans
IDE.
A good example of the OCI driver use is accessing a remote Oracle database from a PHP application
using the Oracle Instant Client libraries. See the OCI 8 and the NetBeans IDE for PHP section in this
tutorial for information on how to enable the OCI8 extension for PHP.
If you have not used Oracle Database XE before, take the Oracle Database XE Getting Started tutorial.
Warning for GlassFish Users: The Oracle Database XE homepage, which you use to administer the database, uses
port 8080 by default. Oracle GlassFish Application Server also uses port 8080 by default. If you run both programs at the
same time, Oracle Database XE blocks browsers from accessing GlassFish at localhost:8080. All applications deployed
on GlassFish return 404 in this case. The simple solution is to shut down Oracle Database XE if you do not need it when
you are running GlassFish. If you need to run both at the same time, change the default port that Oracle Database XE
uses. This is easier than changing the GlassFish default port. There are many sets of instructions on the Internet for
changing the Oracle Database XE default port, including one in Oracle forums.
Establishing a Connection to Oracle Database
In this exercise you will test and create a new connection to the database.
1. Start the Oracle database.
2. Open the Services window (Window > Services or Ctrl-5;-5 on Mac). In the Services window, right-click the
Databases node and choose New Connection.
3. In the New Connection wizard, select Oracle Thin in the Driver dropdown list.
4. Click Add and locate the ojdbc6.jar file that you previously downloaded. Click Next.
5. In the Customize Connection panel of the wizard, enter the following values and click Next.
Value
Name
Driver Name
Host
localhost or 127.0.0.1.
Note: In the case of a remote connection, provide the IP address or
resolvable hostname of the machine where the database is installed.
Port
1521 (default)
Service ID (SID)
Username
Password
6. Click Test Connection to confirm that the IDE is able to connect to the database. Click Next.
If the attempt is successful, the message "Connection succeeded" is displayed in the wizard.
Note: You need to unlock the HR schema before you can access it in NetBeans. Unlocking the HR database is
described in the Oracle Database XE Getting Started tutorial.
The new connection will appear under the Databases node in the Services window. You can expand it and start browsing
the database object's structure.
Change the display name for the connection node: choose Properties from the node's popup menu and click the ellipsis
button for the Display Name property. Enter OracleDB as the Display Name and click OK.
Note. Although the steps above demonstrate the case of connecting to a local database instance, the steps for
connecting to a remote database are the same. The only difference is that instead of specifying localhost as the
hostname, enter the IP address or hostname of the remote machine where Oracle Database is installed.
Manipulating Data in Oracle Database
A common way of interacting with databases is running SQL commands in an SQL editor or by using database
management interfaces. For example, Oracle Database XE has a browser-based interface through which you can
administer the database, manage database objects, and manipulate data.
Although you can perform most of the database-related tasks through the Oracle Database management interface, in this
tutorial we demonstrate how you can make use of the SQL Editor in the NetBeans IDE to perform some of these tasks.
The following exercises demonstrate how to create a new user, quickly recreate a table, and copy the table data.
Creating a User
Let's create a new database user account to manipulate tables and data in the database. To create a new user, you must
be logged in under a database administrator account, in our case, the default system account created during database
installation.
1. In the Services window, right-click the OracleDB connection node and choose Execute Command. This opens the
NetBeans IDE's SQL editor, in which you can enter SQL commands that will be sent to the database.
2. To create a new user, enter the following command in the SQL Editor window and click the Run SQL button on
the toolbar.
4. Right-click the Departments table node and select Grab Structure. Save the .grab file on your disk.
5. Expand the JIM schema, right-click the Tables node and choose Recreate Table.
Point to the .grab file that you created.
6. Review the SQL script that will be used to create the table. Click OK.
When you click OK, the new DEPARTMENTS table is created and appears under the JIM schema node. If you
right-click the table node and choose View Data you will see that the table is empty.
If you want to copy the data from the original Departments table to the new table, you can enter the data manually in the
table editor or run an SQL script on the new table to populate the table.
To enter the data manually, perform the following steps.
1. Right-click the DEPARTMENTS table under the JIM schema and choose View Data.
2. Click the Insert Records icon on the View Data toolbar and to open the Insert Record window.
Value
10
DEPARTMENT_NAME Administration
MANAGER_ID
200
LOCATION_ID
1700
To populate the table using an SQL script, perform the following steps.
1. Right-click the DEPARTMENTS table under the JIM schema and choose Execute Command.
2. Enter the script in the SQL Command tab. Click the Run button in the toolbar.
The following script will populate the first row of the new table with the data from the original table.
INSERT INTO JIM.DEPARTMENTS (DEPARTMENT_ID, DEPARTMENT_NAME, MANAGER_ID,
LOCATION_ID) VALUES (10, 'Administration', 200, 1700);
You can retrieve the SQL script for populating the table from the original table by performing the following steps.
1. Right-click the DEPARTMENTS table under the HR schema and choose View Data.
2. Select all rows in the View Data window, then right-click in the table and choose Show SQL Script for INSERT
from the popup menu to open the Show SQL dialog that contains the script.
You can then copy the script and modify it as necessary to insert the data in your table.
Working with Table Data
To work with table data, you can make use of the SQL Editor in NetBeans IDE. By running SQL queries, you can add,
modify and delete data maintained in database structures.
At first, create the second table named Locations in the jim schema (stay logged under the jim's user account). This time,
we will simply run the ready-to-use SQL file in the IDE:
1. Download and save the locations.sql file to the USER_HOME directory on your computer.
2. Open the Favorites window of the IDE and locate the locations.sql file.
To open the Favorites window, click Window > Favorites in the main menu (press Ctrl-3). The USER_HOME
directory is listed in the Favorites window by default.
3. Right-click the locations.sql file and choose Run File.
Note. If more than one database connection is registered with the IDE, the IDE might prompt you to select the
correct connection.
4. In the Services window, right-click the Tables node and choose Refresh in the popup menu.
You can see that the Locations table with data was added to the JIM schema.
5. Right-click the Locations table node and choose View Data to see the table contents. You will see the contents of
the Locations table.
You can insert new records and modify existing data directly in this view window.
6. Next, we run a query to display information from two tables: Departments and Locations.
In our case, we will use a simple "natural join", because both tables have the same "location_id" column that
holds values of the same data type. This join selects only the rows that have equal values in the matching
location_id column.
Open the SQL Command window (right-click the Tables node under the JIM schema and choose Execute
Command), enter the following SQL statement, and click the Run SQL icon.
SELECT DEPARTMENT_NAME, MANAGER_ID, LOCATION_ID, STREET_ADDRESS, POSTAL_CODE, CITY,
STATE_PROVINCE
FROM departments NATURAL JOIN locations
ORDER by DEPARTMENT_NAME;
This SQL query returns the rows from the Departments table whose location_id values are equal to the values in
the matching column in the Locations table, with the results being ordered by the Department name. Note that
you cannot insert new records directly in the results of this query, as you could do in the representation of a single
table.
You can save the SQL join query as a View (right-click the View node and choose Create View) and run it
conveniently whenever you want. For this, the database user should be granted the privilege to Create View that
our sample user does not have. You can log in under the system account, grant jim the Create View privilege
(with this SQL statement: "grant create view to jim;") and try creating your own view.
Tips for Working in the NetBeans IDE SQL Editor
If you were following this tutorial, you already used the capabilities of the NetBeans IDE SQL Editor. Here we list several
other capabilities of the NetBeans IDE SQL Editor that might be useful to you.
1. GUI View of Database Tables. When you right-click a table node in the Services window and choose View Data,
the IDE displays a visual representation of the table and its data (as shown in the figure above). You can also
add, modify, and delete table data directly in this view.
o To add a record, click the Insert Records
icon and insert new data in the Insert Records window that
opens. Click the Show SQL button to see the SQL code for this operation. The table will be automatically
updated with the new records.
o To modify a record, double-click directly inside any cell in the GUI View of a table and type the new value.
Until the change is committed, the modified text is shown in green. To commit your changes, click the
Commit Changes
icon. To cancel changes, click the Cancel Edits
icon.
o To delete a row, select it and click the Delete Selected Records
icon.
2. Keep Prior Tabs. Click the Keep Prior Tabs icon on the SQL Editor toolbar to keep the windows with the
results of previous queries open. This can be helpful if you want to compare the results of several queries.
3. SQL History (Ctrl-Alt-Shift-H). Use the SQL History icon on the SQL Editor toolbar to view all SQL statements
that you ran for each of the database connections. Choose the connection from the drop-down list, find the SQL
statement that you need and click Insert to place the statement to the SQL Command window.
4. Connection list. If you have several database connections and you need to quickly switch between them in the
SQL Editor, use the Connections drop-down list.
5. Run SQL Statements. To run the entire statement that is currently in the SQL Command window, click the Run
SQL icon. If you want to run only a part of SQL, select it in the SQL Command window, right-click the selection
and choose Run Selection. In this case, only the selected part will be executed.
Troubleshooting
The troubleshooting tips below describe only a few exceptions that we met. If your question is not answered here, make
your own search or use the Send Feedback on This Tutorial link to provide constructive feedback.
In a general case, this means that the NLS_LANG environment variable contains an invalid value for language, territory,
or character set. If this is your case, the invalid NLS_LANG settings should be disabled at your operating system level.
For Windows, rename the NLS_LANG subkey in your Windows registry at
\HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE. For Linux/Unix, run the command "unset NLS_LANG"
Java DB is installed when you install JDK 7 or JDK 8 (except on Mac OS X). If you are using Mac OS X you can
download and install Java DB manually or use the Java DB that is installed by Java EE version of the NetBeans
IDE installer.
1. Run the self-extracting file. A folder named 'javadb' will be created in the same location as the file. If you just
downloaded Java DB and want to have the database server reside in a different location than where it was
extracted to, you should relocate it now.
2. On your system, create a new directory to be used as a home directory for the individual instances of the
database server. For example, you can create this folder in the Java DB root directory (javadb) or in any other
location.
Before continuing further, it is important to understand the components found in Java DB's root directory:
Note. If the Database Location field is empty you will need to set the path to the directory that contains your
databases. You will need to create a directory for the databases if no directory exists.
Starting the Server and Creating a Database
The Java DB Database menu options are displayed when you right-click the Java DB node in the Services window. This
contextual menu items allow you to start and stop the database server, create a new database instance, as well as
register database servers in the IDE (as demonstrated in the previous step). To start the database server:
1. In the Services window, right-click the Java DB node and choose Start Server. Note the following output in the
Output window, indicating that the server has started:
2. Right-click the Java DB node and choose Create Database to open the Create Java DB Database dialog.
3. Type contact for the Database Name.
4. Type nbuser for the User Name and Password. Click OK.
Note. The Database Location is the default location set during installation of Java DB from GlassFish. If you
installed Java DB separately, this location might be different.
After you create the database, if you expand the Databases node in the Services window you can see that the IDE
created a database connection and that the database was added to the list under the Java DB node.
Connecting to the Database
So far, you have successfully started the the database server and created a database instance named contact in the IDE.
In the Services window of the IDE you can perform the following common tasks on database structures.
In order to begin working with the contact database, you need to create a connection to it. To connect to the contact
database perform the following steps.
1. Expand the Databases node in the Services window and locate the new database and the database connection
nodes.
The database connection node(
) is displayed under the Databases node. The name of the database is
displayed under the Java DB node.
Note. You will also see the sample [app on APP] database connection that is the default database schema.
2. Right-click the contact database connection node (jdbc:derby://localhost:1527/contact [nbuser on NBUSER]) and
choose Connect.
The connection node icon appears whole (
3. Create a convenient display name for the database by right-clicking the database connection node
(jdbc:derby://localhost:1527/contact [nbuser on NBUSER]) and choosing Rename. Type Contact DB in the text
field and click OK.
Creating Tables
The contact database that you just created is currently empty. It does not yet contain any tables or data. In NetBeans IDE
you can add a database table by either using the Create Table dialog, or by inputting an SQL statement and running it
directly from the SQL Editor. You can explore both methods:
7. Repeat this procedure now by specifying fields as shown in the table below:
Key
Index
[checked] [checked]
Null
[checked]
[checked]
[checked]
[checked]
[checked]
Data type
INTEGER
VARCHAR
VARCHAR
VARCHAR
DATE
VARCHAR
Size
0
20
20
30
0
60
8. You are creating a table named FRIENDS that holds the following data for each contact record:
o
o
o
o
o
First Name
Last Name
Nick Name
Friend Since Date
Email Address
9. When you are sure that your Create Table dialog contains the same specifications as those shown above, click
OK. The IDE generates the FRIENDS table in the database, and you can see a new FRIENDS table node (
)
display under the Tables node. Beneath the table node the columns (fields) are listed, starting with the primary
key ( ).
differ depending on the database management system. See the JavaDB Reference Manual for specific
guidelines.
10. Click the Run SQL ( ) button in the task bar at the top of the editor (Ctrl-Shift-E) to execute the query. In the
Output window (Ctrl-4), a message displays indicating that the statement was successfully executed.
11. To verify changes, right-click the Contact DB connection node in the Services window and choose Refresh. This
updates the Runtime UI component to the current status of the specified database. This step is necessary when
running queries from the SQL Editor in NetBeans IDE. Note that the new COLLEAGUES table node (
displays under Tables in the Services window.
) now
Write an SQL statement in the SQL Editor that supplies a value for every field present in the table schema.
Use the SQL Editor to add records to the table.
Use an external SQL script to import records to the table.
Read the sections below to learn how to use all these methods of populating the FRIENDS table with data.
Running an SQL Statement
1. Expand the Tables under the Contact DB node in the Services window, right-click the FRIENDS table and choose
Execute Command to open the SQL Editor window.
2. In the SQL Editor, enter the following statement.
INSERT INTO APP.FRIENDS VALUES (1,'Theodore','Bagwell','T-Bag','2004-12-25','[email protected]')
While you are typing, you can use the SQL Editor code completion.
3. Right-click inside the SQL Editor and choose Run Statement. The Output window displays a message indicating
that the statement was successfully executed.
4. To verify that the new record has been added to the FRIENDS table, right-click the FRIENDS table node in the
Services window and choose View Data.
When you choose View Data, a query to select all the data from the table is automatically generated in the upper
pane of the SQL Editor. The results of the statement are displayed in the lower pane of the SQL Editor. In this
case, the FRIENDS table displays in the lower pane. Note that a new row has been added with the data you just
supplied from the SQL statement.
1. Right-click the FRIENDS table node and choose View Data (if you have not done this at the last step of the
previous section).
2. Click the Insert Record(s) (Alt-I) button to add a row.
The Insert Records dialog box appears.
3. Click in each cell and enter records. Note that for the cells with Date data type, you can choose a date from the
calendar. Click OK when you are done.
In the SQL Editor, you can sort the results by clicking on a row header, modify and delete existing records, and
see the SQL script for the actions you are doing in the editor (the Show SQL Script command from the pop-up
menu).
Deleting Tables
In the following step, you use an external SQL script to create a new COLLEAGUES table. However, you just created a
COLLEAGUES table in the Using the SQL Editor section above. In order to make it clear that the SQL script indeed
creates a new table, you can delete the already created COLLEAGUES table now. To delete a database table perform the
following steps.
1. Expand the Tables node under the database connection node in the Services window.
2. Right-click the table that you want to delete and choose Delete.
Using an External SQL Script
Issuing commands from an external SQL script is a popular way to manage your database. You may have already
created an SQL script elsewhere, and want to import it into NetBeans IDE to run it on a specified database.
In this exercise the script will create a new table named COLLEAGUES and populate it with data. Perform the following
steps to run the script on the contact database.
1. Download colleagues.sql to your local system
2. Choose File > Open File from the IDE's main menu. In the file browser navigate to the location of the saved
colleagues.sql file and click Open. The script automatically opens in the SQL Editor.
Alternatively, you can copy the contents of colleagues.sql and then open the SQL editor and paste the contents of
the file into the SQL editor.
3. Make sure your connection to Contact DB is selected from the Connection drop-down box in the tool bar at the
top of the editor.
4. Click the Run SQL ( ) button in the SQL Editor's task bar. The script is executed against the selected database,
and any feedback is generated in the Output window.
5. To verify changes, right-click the Contact DB connection node in the Services window and choose Refresh. Note
that the new COLLEAGUES table from the SQL script now displays as a table node under contact in the Services
window.
6. To view the data contained in the new tables, right-click the COLLEAGUES table and choose View Data. In this
manner, you can also compare the tabular data with the data contained in the SQL script to see that they match.
Recreating Tables from a Different Database
If you have a table from another database which you would like to recreate in the database you are working in from
NetBeans IDE, the IDE offers a handy tool for this. You first need to have the second database registered in the IDE,
similar to what was described at the beginning of this tutorial. For the purposes of this tutorial, use the sample database
that comes packaged with Java DB. This process is essentially carried out in two parts: You first 'grab' the table definition
of the selected table, then you can recreate the table in your chosen database:
1. Connect to the sample database by right-clicking the connection node under the Databases node in the Services
window and choosing Connect (username and password is app).
2. Expand the Tables node under the sample database connection, right-click the CUSTOMER table node and
choose Grab Structure.
3. In the Grab Table dialog that opens, specify a location on your computer to save the grab file that will be created.
Click Save.
The grab file records the table definition of the selected table.
4. Expand the APP schema node under the Contact DB database connection, right-click the Tables node and
choose Recreate Table to open the Recreate Table dialog box.
5. In the Recreate Table dialog box, navigate to the location where you saved the CUSTOMER grab file and click
Open to open the Name the Table dialog box.
6. At this point you can change the table name or edit the table definition. Otherwise, click OK to immediately create
the table in the contact database. A new CUSTOMER table node appears beneath the Contact DB connection
node.
If you view the data in the new CUSTOMER table you will see that there are no records in the database, but that the
structure of the table is identical to the table that you grabbed
Version Required
7.2, 7.3, 7.4, 8.0, Java
version 5.x
Note: This tutorial assumes that you already have the MySQL RDBMS installed and configured on your computer. If you
are installing for the first time, please refer to the official MySQL documentation for help. You can also refer to Setting Up
the MySQL Database Server in the Windows Operating System.
Configuring MySQL Server Properties
NetBeans IDE comes bundled with support for the MySQL RDBMS. Before you can access the MySQL Database Server
in NetBeans IDE, you must configure the MySQL Server properties.
1. Right-click the Databases node in the Services window and choose Register MySQL Server to open the MySQL
Server Properties dialog box.
2. Confirm that the server host name and port are correct.
Notice that the IDE enters localhost as the default server host name and 3306 as the default server port number.
3. Enter the Administrator user name (if not displayed).
Note: You need administrative access to be able to create and remove databases.
4. Enter the Administrator password. The default is set to blank.
Note: A blank password can also be a password.
5. Click the Admin Properties tab at the top of the dialog box.
The Admin Properties tab is then displayed, allowing you to enter information for controlling the MySQL Server.
6. In the Path/URL to admin tool field, type or browse to the location of your MySQL Administration application such
as the MySQL Admin Tool, PhpMyAdmin, or other web-based administration tools.
Note: mysqladmin is the MySQL admin tool found in the bin folder of the MySQL installation directory. It is a
command-line tool and not ideal for use with the IDE.
Type any arguments for the admin tool in the Arguments field.
7. In the Path to start command, type or browse to the location of the MySQL start command. To find the start
command, look for mysqld in the bin folder of the MySQL installation directory.
Note: The recommended binary for Unix and NetWare is mysql_safe. The start command may also vary if
MySQL was installed as part of an AMP installation.
Type any arguments for the start command in the Arguments field.
8. In the Path to stop command field, type or browse to the location of the MySQL stop command. This is usually the
path to mysqladmin in the bin folder of the MySQL installation directory. If the command is mysqladmin, in the
Arguments field, type -u root stop to grant root permissions for stopping the server.
9. When finished, the Admin Properties tab should resemble the following figure. If you are satified with your
configuration, click OK.
When the server is connected you will be able to expand the MySQL Server node and view the all available MySQL
databases.
Creating and Connecting to the Database Instance
A common way of interacting with databases is through an SQL editor. NetBeans IDE has a built-in SQL Editor for this
purpose. The SQL Editor is generally accessible via the Execute Command option from the right-click menu of the
connection node (or of the connection node's child nodes). Now that you are connected to the MySQL server, you can
create a new database instance using the SQL Editor. For purposes of this tutorial, create an instance called
MyNewDatabase:
1. In the IDE's Services window, right-click the MySQL Server node and choose Create Database.
The Create MySQL Database dialog box opens.
2. In the Create MySQL Database dialog box, type the name of the new database. We will use MyNewDatabase for
this tutorial. Leave the checkbox unselected at this time.
Note: You can also grant full access to a given user. By default, only the admin user has the permissions to
perform certain commands. The drop down list lets you assign these permissions to a specified user.
3. Click OK.
The new database appears under the MySQL Server node in the Services window.
4. Right-click the new database node and choose Connect in the popup menu to open the connection to the
database.
Database connections that are open are represented by a complete connection node (
window.
) in the Services
11.
12.
13. To execute the query, either click the Run SQL ( ) button in the task bar at the top (Ctrl-Shift-E), or right-click
within the SQL Editor and choose Run Statement. The IDE generates the Counselor table in the database, and
you receive a message similar to the following in the Output window.
14. To verify changes, right-click the Tables node in the Database Explorer and choose Refresh. The Refresh option
updates the Database Explorer's UI component to the current status of the specified database. Note that the new
Counselor table node ( ) now displays under Tables in the Database explorer. If you expand the table node you
can see the columns (fields) you created, starting with the primary key ( ).
In the Database Explorer, right-click the Tables node and choose Create Table. The Create Table dialog opens.
In the Table name text field, type Subject.
Click Add Column.
For the Name of the column, enter id. Choose SMALLINT for data type from the Type drop-down list. Click OK.
5. Select the Primary Key check box in the Add Column dialog box. You are specifying the primary key for your
table. All tables found in relational databases must contain a primary key. Note that when you select the Key
check box, the Index and Unique check boxes are also automatically selected and the Null check box is
deselected. This is because primary keys are used to identify a unique row in the database, and by default form
the table index. Because all rows need to be identified, primary keys cannot contain a Null value.
6. Repeat this procedure by adding the remaining columns, as shown in the following table.
Key
Index
Null
[checked] [checked]
SMALLINT 0
[checked]
name
VARCHAR 50
[checked]
description
VARCHAR 500
[checked]
FK_counselorID SMALLINT 0
7. You are creating a table named Subject that will hold data for each of the following records.
o Name: name of the subject
o Description: description of the subject
o Counselor ID: counselor ID that corresponds to an ID from the Counselor table
Make sure that the fields in your Create Table dialog match those shown above, then click OK. The IDE
generates the Subject table in the database, and you can see a new Subject table node ( ) immediately display
under Tables in the Database Explorer.
Working with Table Data
In order to work with table data, you can make use of the SQL Editor in NetBeans IDE. By running SQL queries on a
database, you can add, modify and delete data maintained in database structures. To add a new record (row) to the
Counselor table, do the following:
1. Choose Execute Command from the Tables folder in the Database Explorer. A blank canvas opens in the SQL
Editor in the main window.
2. In the SQL Editor, type in the following query.
3. INSERT INTO Counselor
VALUES (1, 'Ricky', '"The Dragon"', 'Steamboat','334 612-5678', '[email protected]', '1996-01-01')
4. To execute the query, right-click within the SQL Editor and choose Run Statement. In the Output window, you can
see a message indicating that the query was successfully executed.
5. To verify that the new record has been added to the Counselor table, in the Database Explorer, right-click the
Counselor table node and choose View Data. A new SQL Editor pane opens in the main window. When you
choose View Data, a query to select all the data from the table is automatically generated in the upper region of
the SQL Editor. The results of the statement are displayed in a table view in the lower region. In this example, the
Counselor table displays. Note that a new row has been added with the data you just supplied from the SQL
query.
3. Click the Run SQL ( ) button in the SQL Editor's task bar. The script is executed against the selected database,
and any feedback is generated in the Output window.
4. To verify changes, right-click the MyNewDatabase connection node in the Runtime window and choose Refresh.
The Refresh option updates the Database Explorer's UI component to the current status of the specified
database. Note that the two new tables from the SQL script now display as a table nodes under MyNewDatabase
in the Database Explorer.
5. Choose View Data from the right-click menu of a selected table node to see the data contained in the new tables.
In this manner, you can compare the tabular data with the data contained in the SQL script to see that they match
The table data used in that tutorial is contained in ifpwafcad.sql and is also required for this tutorial. This SQL file creates
two tables, Subject and Counselor, then populates them with sample data. If needed, save this file to your computer, then
open it in the NetBeans IDE and run it on the MySQL database named MyNewDatabase.
To follow this tutorial, you need the following software and resources.
Software or Resource
Version Required
NetBeans IDE
version 7 or 8
5.x
version 5.x
Notes:
The Java download bundle of the NetBeans IDE enables you to install the GlassFish server. You require the
GlassFish server to work through this tutorial.
The MySQL Connector/J JDBC Driver, necessary for communication between Java platforms and the MySQL
database protocol, is included in the NetBeans IDE.
If you need to compare your project with a working solution, you can download the sample application.
The welcome page (index.jsp) presents the user with a simple HTML form. When a browser requests index.jsp, the JSTL
code within the page initiates a query on MyNewDatabase. It retrieves data from the Subject database table, and inserts it
into to the page before it is sent to the browser. When the user submits his or her selection in the welcome page's HTML
form, the submit initiates a request for the response page (response.jsp). Again, the JSTL code within the page initiates a
query on MyNewDatabase. This time, it retrieves data from both the Subject and Counselor tables and inserts it into to the
page, allowing the user to view data based upon his or her selection when the page is returned to the browser.
In order to implement the scenario described above, you develop a simple application for a fictitious organization named
IFPWAFCAD, The International Former Professional Wrestlers' Association for Counseling and Development.
index.jsp
response.jsp
The New Project wizard allows you to create an empty web application in a standard IDE project. The standard
project uses an IDE-generated Ant build script to compile, deploy, and run the application.
2. In Project Name, enter IFPWAFCAD. Also, specify the location for the project on your computer. (By default, the
IDE places projects in a NetBeansProjects folder located in your home directory.) Click Next.
3. In the Server and Settings panel, specify the GlassFish server as server which will be used to run the application.
Note. The GlassFish server displays in the Server drop-down field if you installed the Java version of the
NetBeans IDE. Because the GlassFish server is included in the download, it is automatically registered with the
IDE. If you want to use a different server for this project, click the Add button located next to the Server drop-down
field, and register a different server with the IDE. However, working with servers other than the GlassFish server
is beyond the scope of this tutorial.
4. In the Java EE Version field, select Java EE 5.
Java EE 6 and Java EE 7 web projects do not require the use of the web.xml deployment descriptor, and the
NetBeans project template does not include the web.xml file in Java EE 6 and Java EE 7 projects. However, this
tutorial demonstrates how to declare a data source in the deployment descriptor, and it does not rely on any
features specific to Java EE 6 or Java EE 7, so you can set the project version to Java EE 5.
Note. You could equally set the project version to Java EE 6 or Java EE 7 and then create a web.xml deployment
descriptor. (From the New File wizard, select the Web category, then Standard Deployment Descriptor.)
5. Click Finish. The IDE creates a project template for the entire application, and opens an empty JSP page
(index.jsp) in the editor. The index.jsp file serves as the welcome page for the application.
Preparing the Web Interface
Begin by preparing the welcome (index.jsp) and response (response.jsp) pages. The welcome page implements an HTML
form that is used to capture user data. Both pages implement an HTML table to display data in a structured fashion. In this
section, you also create a stylesheet that enhances the appearance of both pages.
You can configure the Palette to your liking - right-click in the Palette and choose Show Big Icons and Hide Item
Names to have it display as in the image above.
4. Place your cursor at a point just after the <h1> tags. (This is where you want to implement the new HTML table.)
Then, in the Palette, double-click the Table icon.
5. In the Insert Table dialog that displays, specify the following values then click OK:
o
o
o
Rows: 2
Columns: 1
Border Size: 0
8. Type in the following content between the <form> tags (new content shown in bold):
<tr>
<td>
<form action="response.jsp">
<strong>Select a subject:</strong>
</form>
</td>
</tr>
9. Press Enter to add an empty line after the content you just added and then double-click Drop-down List in the
Palette to open the Insert Drop-down dialog box.
10. Type subject_id for the Name text field in the Insert Drop-down dialog and click OK. Note that the code snippet for
the drop-down list is added to the form.
The number of options for the drop-down is currently not important. Later in the tutorial you will add JSTL tags
that dynamically generate options based on the data gathered from the Subject database table.
11. Add a submit button item ( ) to a point just after the drop-down list you just added. You can either use the
Palette to do this, or invoke the editor's code completion as illustrated in the previous step. In the Insert Button
dialog, enter submit for both the Label and Name text fields, then click OK.
12. To format your code, right-click in the editor and choose Format (Alt-Shift-F; Ctrl-Shift-F on Mac). Your code is
automatically formatted, and should now look similar to the following:
<body>
<h2>Welcome to <strong>IFPWAFCAD</strong>, the International Former
Professional Wrestlers' Association for Counseling and Development!
</h2>
<table border="0">
<thead>
<tr>
<th>IFPWAFCAD offers expert counseling in a wide range of fields.</th>
</tr>
</thead>
<tbody>
<tr>
<td>To view the contact details of an IFPWAFCAD certified former
professional wrestler in your area, select a subject below:</td>
</tr>
<tr>
<td>
<form action="response.jsp">
<strong>Select a subject:</strong>
<select name="subject_id">
<option></option>
</select>
<input type="submit" value="submit" name="submit" />
</form>
</td>
</tr>
</tbody>
</table>
</body>
To view this page in a browser, right-click in the editor and choose Run File (Shift-F6; Fn-Shift-F6 on Mac). When
you do this, the JSP page is automatically compiled and deployed to your server. The IDE opens your default
browser to display the page from its deployed location.
<tr>
<td><strong>Contact Details: </strong></td>
<td><strong>email: </strong>
<a href="mailto:{placeholder}">{placeholder}</a>
<br><strong>phone: </strong>{placeholder}
</td>
</tr>
</tbody>
</table>
To view this page in a browser, right-click in the editor and choose Run File (Shift-F6; Fn-Shift-F6 on Mac). The
page compiles, is deployed to the GlassFish server, and opens in your default browser.
Creating a stylesheet
Create a simple stylesheet that enhances the display of the web interface. This tutorial assumes that you understand how
style rules function, and how they affect corresponding HTML elements found in index.jsp and response.jsp.
1. Open the New File wizard by pressing the New File (
) button in the IDE's main toolbar. Select the Web
category, then select Cascading Style Sheet and click Next.
2. Type style for CSS File Name and click Finish. The IDE creates an empty CSS file and places it in the same
project location as index.jsp and response.jsp. Note that a node for style.css now displays within the project in the
Projects window, and the file opens in the editor.
3. In the editor, add the following content to the style.css file:
body {
font-family: Verdana, Arial, sans-serif;
font-size: smaller;
padding: 50px;
color: #555;
}
h1 {
text-align: left;
letter-spacing: 6px;
font-size: 1.4em;
color: #be7429;
font-weight: normal;
width: 450px;
}
table {
width: 580px;
padding: 10px;
background-color: #c5e7e0;
}
th {
text-align: left;
The JDBC data source relies on JNDI, the Java Naming and Directory Interface. The JNDI API provides a uniform
way for applications to find and access data sources. For more information, see The JNDI Tutorial.
3. Optionally, add a description for the data source. For example, type in: Accesses the database that provides data
for the IFPWAFCAD application.
4. Click Next, then click Next again to skip step 3, Additional Properties.
5. In Step 4, type in IfpwafcadPool for JDBC Connection Pool Name. Make sure the Extract from Existing
Connection option is selected, and choose jdbc:mysql://localhost:3306/MyNewDatabase from the drop-down list.
Click Next.
Note: The wizard detects any database connections that have been set up in the IDE. Therefore, you need to
have already created a connection to the MyNewDatabase database at this point. You can verify what
connections have been created by opening the Services window (Ctrl-5; -5 on Mac) and looking for connection
nodes ( ) under the Databases category.
6. In Step 5, select javax.sql.ConnectionPoolDataSource in the Resource Type drop-down list.
Note that the IDE extracts information from the database connection you specified in the previous step, and sets
name-value properties for the new connection pool.
7. Click Finish. The wizard generates a glassfish-resources.xml file that contains entries for the data source and
connection pool you specified.
In the Projects window, you can open the glassfish-resources.xml file that was created under the Server Resources node
and note that, within the <resources> tags, a data source and connection pool have been declared containing the values
you previously specified.
To confirm that a new data source and connection pool are indeed registered with the GlassFish server, you can deploy
the project to the server, then locate the resources in the IDE's Services window:
1. In the Projects window, right-click the IFPWAFCAD project node and choose Deploy. The server starts up if not
already running, and the project is compiled and deployed to it.
2. Open the Services window (Ctrl-5; -5 on Mac) and expand the Servers > GlassFish > Resources > JDBC >
JDBC Resources and Connection Pools nodes. Note that the new data source and connection pool are now
displayed:
The new resource is now listed under the Resource References heading.
6. To verify that the resource is now added to the web.xml file, click the Source tab located along the top of the
editor. Notice that the following <resource-ref> tags are now included.
<resource-ref>
<description>Database for IFPWAFCAD application</description>
<res-ref-name>jdbc/IFPWAFCAD</res-ref-name>
<res-type>javax.sql.ConnectionPoolDataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
Adding the database driver's JAR file to the server
Adding the database driver's JAR file is another step that is vital to enabling the server to communicate with your
database. Ordinarily, you would need to locate your database driver's installation directory and copy the mysql-connectorjava-5.1.6-bin.jar file from the driver's root directory into the library folder of the server you are using. Fortunately, the
IDE's server management is able to detect at deployment whether the JAR file has been added - and if not, it does so
automatically.
In order to demonstrate this, open the Servers manager (Choose Tools > Servers). The IDE provides a JDBC driver
deployment option. If the option is enabled, it initiates a check to determine whether any drivers are required for the
server's deployed applications. In the case of MySQL, if the driver is required and it is missing, the IDE's bundled driver is
deployed to the appropriate location on the server.
1. Choose Tools > Servers to open the Servers manager. Select the GlassFish server in the left pane.
2. In the main pane, select the Enable JDBC Driver Deployment option.
3. Before you close the Servers manager, make a note of the path indicated in the Domains folder text field. When
you connect to the GlassFish server in the IDE, you are actually connecting to an instance of the application
server. Each instance runs applications in a unique domain, and the Domain Name field indicates the name of the
domain your server is using. As shown in the image above, the driver JAR file should be located within domain1,
which is the default domain created upon installing the GlassFish server.
4. Click Close to exit the Servers manager.
5. On your computer, navigate to the GlassFish server installation directory and drill into the domains > domain1 >
lib subfolder. Because you should have already deployed the IFPWAFCAD project to the server, you should see
the mysql-connector-java-5.1.6-bin.jar file. If you do not see the driver JAR file, perform the following step.
6. Deploy your project to the server. In the IDE's Projects window, choose Deploy from the right-click menu of the
project node. You can view progress in the IDE's Output window (Ctrl-4; -4 on Mac). The output indicates that
the MySQL driver is deployed to a location in the GlassFish server.
Now, if you return to the domain1/lib subfolder on your computer, you can see that the mysql-connector-java5.1.6-bin.jar file has been automatically added.
core: common, structural tasks such as iterators and conditionals for handling flow control
fmt: internationalization and localization message formatting
sql: simple database access
xml: handling of XML content
This tutorial focuses on usage of the core and sql tag libraries.
Implementing JSTL code
Now you can implement the code that dynamically retrieves and displays data for each page. Both pages require that you
implement an SQL query that utilizes the data source created earlier in the tutorial.
The IDE provides several database-specific JSTL snippets which you can select from the Palette (Ctrl-Shift-8; -Shift-8
on Mac).
index.jsp
In order to dynamically display the contents of the form in index.jsp, you need to access all names from the Subject
database table.
1. Hover your mouse over the DB Report item in the Palette.
The DB Report item uses the <sql:query> tag to create an SQL query, then it uses the <c:forEach> tag to loop
through the query's resultset and output the retrieved data.
2. Place your cursor above the <%@page ... %> declaration (line 7), then double-click the DB Report item in the
Palette. In the dialog that displays, enter the following details:
o Variable Name: subjects
o Scope: page
o Data Source: jdbc/IFPWAFCAD
o Query Statement: SELECT subject_id, name FROM Subject
3. Click OK. The following content is generated in the index.jsp file. (New content shown in bold.)
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
<%-Document : index
Author : nbuser
--%>
<sql:query var="subjects" dataSource="jdbc/IFPWAFCAD">
SELECT subject_id, name FROM Subject
</sql:query>
<table border="1">
<!-- column headers -->
<tr>
<c:forEach var="columnName" items="${subjects.columnNames}">
<th><c:out value="${columnName}"/></th>
</c:forEach>
</tr>
<!-- column data -->
<c:forEach var="row" items="${subjects.rowsByIndex}">
<tr>
<c:forEach var="column" items="${row}">
<td><c:out value="${column}"/></td>
</c:forEach>
</tr>
</c:forEach>
</table>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
Note that the IDE automatically added taglib directives needed for the JSTL tags used in the generated content
(<sql:query> and <c:forEach>). A taglib directive declares that the JSP page uses custom (i.e., JSTL) tags,
names the tag library that defines them, and specifies their tag prefix.
4. Run the project to see how it displays in a browser. Right-click the project node in the Projects window and
choose Run.
When you choose Run, the IDE deploys the project to the GlassFish server, the index page is compiled into a
servlet, and the welcome page opens in your default browser. The code generated from the DB Report item
creates the following table in the welcome page.
As you can see, the DB Report item enables you to quickly test your database connection, and enables you to
view table data from the database in your browser. This can be particularly useful when prototyping.
The following steps demonstrate how to integrate the generated code into the HTML drop-down list you created
earlier in the tutorial.
5. Examine the column data in the generated code. Two <c:forEach> tags are used; one is nested inside the other.
This causes the JSP container (i.e., the GlassFish server) to perform a loop on all table rows, and for each row, it
loops through all columns. In this manner, data for the entire table is displayed.
6. Integrate the <c:forEach> tags into the HTML form as follows. The value of each item becomes the subject_id,
and the output text becomes the name, as recorded in the database. (Changes are displayed in bold).
<form action="response.jsp">
<strong>Select a subject:</strong>
<select name="subject_id">
<c:forEach var="row" items="${subjects.rowsByIndex}">
<c:forEach var="column" items="${row}">
<option value="<c:out value="${column}"/>"><c:out value="${column}"/></option>
</c:forEach>
</c:forEach>
</select>
<input type="submit" value="submit" name="submit" />
</form>
An alternative, simpler way to integrate the <c:forEach> tags into the HTML form would be as follows.
<form action="response.jsp">
<strong>Select a subject:</strong>
<select name="subject_id">
<c:forEach var="row" items="${subjects.rows}">
<option value="${row.subject_id}">${row.name}</option>
</c:forEach>
</select>
o
o
o
o
3. Click OK. The following content is generated in the response.jsp file. (New content shown in bold.)
<%@taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
<%-Document : response
Created on : Dec 22, 2009, 8:52:57 PM
Author : nbuser
--%>
<sql:query var="counselorQuery" dataSource="jdbc/IFPWAFCAD">
SELECT * FROM Subject, Counselor
WHERE Counselor.counselor_id = Subject.counselor_idfk
AND Subject.subject_id = ? <sql:param value="${param.subject_id}"/>
</sql:query>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
Note that the IDE automatically added the taglib directive needed for the <sql:query> tag. Also, note that you used
an <sql:param> tag directly within the query. Because this query relies on the subject_id value that was submitted
from index.jsp, you can extract the value using an EL (Expression Language) statement in the form of
${param.subject_id}, and then pass it to the <sql:param> tag so that it can be used in place of the SQL question
mark (?) during runtime.
4. Use a <c:set> tag to set a variable that corresponds to the first record (i.e., row) of the resultset returned from the
query. (New content shown in bold.)
<sql:query var="counselorQuery" dataSource="jdbc/IFPWAFCAD">
SELECT * FROM Subject, Counselor
WHERE Counselor.counselor_id = Subject.counselor_idfk
AND Subject.subject_id = ? <sql:param value="${param.subject_id}"/>
</sql:query>
) button in the main toolbar. The index.jsp page opens in the IDE's default browser.
When index.jsp displays in the browser, select a subject from the drop-down list and click submit. You should now be
forwarded to the response.jsp page, showing details corresponding to your selection.
This concludes the Creating a Simple Web Application Using a MySQL Database tutorial. This document demonstrated
how to create a simple web application that connects to a MySQL database. It also demonstrated how to construct an
application using a basic two-tier architecture, and utilized numerous technologies including JSP, JSTL, JDBC, and JNDI
as a means of accessing and displaying data dynamically.
Troubleshooting
Most of the problems that occur with the tutorial application are due to communication difficulties between the GlassFish
Server Open Source Edition and the MySQL database server. If your application does not display correctly, or if you are
receiving a server error, the following examinations may be useful.
To connect to the MySQL database server, right-click the MySQL Server node and choose Connect.
If a connection node (
) for MyNewDatabase does not display in the Services window, you can create a
connection by right-clicking the MySQL driver node (
) and choosing Connect Using. Enter the required details
in the dialog that displays.
The fields provided in the New Database Connection dialog mirror the URL string entered in the Show JDBC URL
option. Therefore, if you know the URL (e.g., jdbc:mysql://localhost:3306/MyNewDatabase) you can paste it into
the Show JDBC URL field, and the remaining dialog fields become automatically populated.
To ensure that the Subject and Counselor tables exist and that they contain sample data, expand the
MyNewDatabase connection node (
) and locate the MyNewDatabase catalog node ( ). Expand the catalog
node to view existing tables. You can view table data by right-clicking a table node and choosing View Data.
Expand the Servers > the GlassFish Server > Resources node. Expand JDBC Resources to view the
jdbc/IFPWAFCAD data source that was created from glassfish-resources.xml. Expand the Connection Pools node
to view the IfpwafcadPool connection pool that was created from glassfish-resources.xml. (This is demonstrated
above.)
Locate the GlassFish server installation folder on your computer and drill down into the GlassFish
domains/domain1/lib subfolder. Here you should find the mysql-connector-java-5.1.6-bin.jar file.
To set your password to nbuser, navigate to your MySQL installation's bin directory in the command-line prompt
and enter the following:
shell> mysql -u root
mysql> UPDATE mysql.user SET Password = PASSWORD('nbuser')
-> WHERE User = 'root';
mysql> FLUSH PRIVILEGES;
For more information, see the official MySQL Reference Manual: Securing the Initial MySQL Accounts.
6. If the ping fails, click the Additional Properties tab and ensure that the listed property values are correctly set.
Setting Up the MySQL Database Server in the Windows Operating System
The MySQL database server is one of the most popular open-source database servers commonly used in web application
development.
This document recommends a sequence of steps to set up the MySQL database server 5.6 versions in the Windows
operating system. It does not cover MySQL configuration details, it describes a sequence of required steps.
For information about installing and configuring MySQL database server for other operating systems, refer to the Installing
and Upgrading MySQL documentation.
Note: The Setting Up the MySQL Database Server 5.1 versions in the Windows Operating System document provides the
instructions on setting up the 5.1 versions of MySQL Server on Windows.
Contents
3. On the License Information panel, review the license agreement, click the acceptance checkbox, and click Next.
4. On the Find latest products panel, click Execute.
When the operation is complete, click Next.
5. On the Setup Type panel, choose the Custom option and click Next.
6. On the Feature Selection panel, ensure MySQL Server 5.6.x is selected, and click Next.
7. On the Check Requirements panel, click Next.
8. On the Installation panel, click Execute.
When the server installation is completed successfully, the information message appears on the Installation
panel. Click Next.
9. On the Configuration panel, click Next.
10. At the first MySQL Server Configuration page (1/3), set the following options:
o Server Configuration Type. Select the Development Machine option.
o Enable TCP/IP Networking. Ensure the checkbox is selected and specify the options below:
Port Number. Specify the connection port. The default setting is 3306 - leave it unchanged if
there is not special reason to change it.
Open Firewall port for network access. Select to add firewall exception for the specified port.
o Advanced Configuration. Select the Show Advanced Options checkbox to display an additional
configuration page for setting advanced options for the server instance if required.
Note: Choosing this option is necessary to get to the panel for setting the network options where you will
turn off the firewall for the port used by the MySQL server.
11. Click Next.
12. At the second MySQL Server Configuration page (2/3), set the following options:
o Root Account Password.
MySQL Root Password. Enter the root user's password.
Repeat Password. Retype the root user's password.
Note: The root user is a user who has full access to the MySQL database server - creating, updating, and
removing users, and so on. Remember the root password - you will need it later when creating a sample
database.
o
MySQL User Accounts. Click Add User to create a user account. In the MySQL User Details dialog box,
enter a user name, a database role, and a password (for example, !phpuser). Click OK.
Click Next.
13. At the third MySQL Server Configuration page (3/3), set the following options:
o Windows Service Name. Specify a Windows Service Name to be used for the MySQL server instance.
o Start the MySQL Server at System Startup. Leave the checkbox selected if the MySQL server is
required to automatically start at system startup time.
o Run Windows Service as. Choose either:
Standard System Account. Recommended for most scenarios.
Custom User. An existing user account recommended for advanced scenarios.
Click Next.
14. At the Configuration Overview page, click Next.
15. When the configuration is completed successfully, the information message appears on the Complete panel. Click
Finish.
Note: To check that the installation has completed successfully, run the Task Manager. If the MySQLd-nt.exe is
on the Processes list - the database server is running.