Connecting to Oracle Database From NetBeans IDE

September 10, 2017 | Author: GiovanniBanegas | Category: Sql, Databases, Database Index, Net Beans, Oracle Database
Share Embed Donate


Short Description

BAse de datos y Netbeans...

Description

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

Java Development Kit (JDK) Version 7 or 8 Oracle Database XE

10 g Express Edition

Oracle JDBC driver

ojdbc6.jar

Before You Begin Before you start walking through this tutorial, consider the following: 



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

Oracle Thin (with Service ID (SID))

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)

XE (default SID for Oracle Database XE). Note: If you are connecting to a remote database, ask the database administrator to provide you with the database SID.

Username

Password

Enter the username. For the purpose of our tutorial, enter system (the default database administrator account) and password that you used during database installation. Enter the password for the selected username.

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.

7. Select HR in the Select Schema dropdown list. Click Finish.

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.

create user jim identified by mypassword default tablespace users temporary tablespace temp quota unlimited on users; This command creates a new user jim with the password mypassword. The default tablespace is users and the allocated space is unlimited. 3. The next step is to grant the jim user account privileges to do actions in the database. We need to allow the user to connect to the database, create and modify tables in user's default tablespace, and access the Employees table in the sample hr database. In real life, a database administrator creates custom roles and fine tunes privileges for each role. However, for the purpose of our tutorial, we can use a predefined role, such as CONNECT. For more information about roles and privileges, see Oracle Database Security Guide. grant connect to jim; grant create table to jim; grant select on hr.departments to jim; Tablespaces in Oracle Databases A tablespace is a logical database storage unit of any Oracle database. In fact, all of the database's data is stored in tablespaces. You create tables within allocated tablespaces. If a default tablespace is not explicitly assigned to a user, the system tablespace is used by default (it is better to avoid this situation) Creating a Table There are several ways to create a table in the database through the NetBeans IDE. For example, you can run an SQL file (right-click the file and choose Run File), execute an SQL Command (right-click the connection node and choose Execute Command) or use the Create Table dialog box (right-click the Tables node and choose Create Table). In this exercise you will recreate a table by using the structure of another table. In this example, you want the user jim to create a copy of the Departments table in his schema by recreating the table from the hr database. Before you create the table you will need to disconnect from the server and log in as user jim. 1. Right-click the OracleDB connection node in the Services window and choose Disconnect. 2. Right-click the OracleDB connection node and choose Connect and log in as jim. 3. Expand the Tables node under the HR schema and confirm that only the Departments table is accessible to user jim. When you created the user jim, the Select privilege was limited to the Departments table.

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.

3. Type in the fields to enter the data. Click OK. For example, you can enter the following values taken from the original DEPARTMENTS table. Column DEPARTMENT_ID

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.

OCI 8 and the NetBeans IDE for PHP You can use the OCI 8 PHP extension and the NetBeans IDE for PHP to write PHP code that communicates with an Oracle database. To use NetBeans IDE for PHP and an Oracle database: 1. Set up the PHP environment as described in the Configuring Your Environment for PHP Development section of the PHP Learning Trail. Note that NetBeans IDE supports only PHP 5.2 or 5.3. 2. Open your php.ini file in an editor. Make certain that the extension_dir property is set to the PHP extensions directory. This directory is usually PHP_HOME/ext. For example, with PHP 5.2.9 installed to the root directory of C:, the extension_dir setting should be extension_dir="C:\php-5.2.9\ext". 3. Locate and uncomment the line extension=php_oci8_11g.dll (for Oracle 11g) or extension=php_oci8.dll (for Oracle 10.2 or XE). Only one of these extensions can be enabled at one time. Important: If there is no such line in php.ini, look in the extensions folder for the OCI 8 extension file. If there is no OCI 8 extension file in your extensions folder, see Installing PHP and the Oracle Instant Client for Linux and Windows for information about downloading and installing OCI 8. 4. Restart Apache. (Windows users should restart their computer.) 5. Run phpinfo(). If you successfully enabled OCI 8, an OCI 8 section appears in phpinfo() output. When OCI 8 is enabled, NetBeans IDE for PHP accesses this extension for code completion and debugging.

Using OCI JDBC Driver with the NetBeans IDE OCI driver packages are available in the same JAR file as the JDBC Thin driver (ojdbc6.jar). The selection of which driver to use depends on the interface: oracle.jdbc.OracleDriver for the Thin driver and oracle.jdbc.driver.OracleDriver for the OCI driver. To use the OCI driver, you must also install the Oracle Database Instant Client, because it contains all the libraries required for the OCI driver to communicate with the database. To connect to Oracle Database from the NetBeans IDE by using the Oracle's OCI driver: 1. Download the "Basic" package of Oracle Database Instant Client for your platform. Follow the installation instructions on this page. 2. In the IDE's Services window, right-click the Databases node and choose New Connection. 3. In the Locate Driver step, choose Oracle OCI, click Add and specify the ojdbc6.jar file. 4. In the Customize Connection dialog box, provide the connection details: IP address, port, SID, username and password. Notice the difference in the JDBC URL for the OCI and Thin drivers.

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

You see the error similar to the following: Shutting down v3 due to startup exception : No free port within range: >> 8080=com.sun.enterprise.v3.services.impl.monitor.MonitorableSelectorHandler@7dedad This happens because both the GlassFish application server and Oracle Database use port 8080. So, if you want to use both applications at the same time, you need to change this default port of one of them. To reset the default port of the Oracle Database, you can use this command: CONNECT SYSTEM/password EXEC DBMS_XDB.SETHTTPPORT();



You receive the following error: Listener refused the connection with the following error: ORA-12505, TNS:listener does not currently know of SID given in connect descriptor. This happens when the Service ID (SID) of the database instance provided by the connect descriptor is not known to the listener. There are a number of causes for this exception. For example, it might occur if Oracle Database has not been started (simplest case). Or the SID is incorrect or not known to the listener. If you use a default SID (e.g. for Oracle Database Express Edition, the default SID is XE), this problem is unlikely to appear. The SID is included in the CONNECT DATA parts in the tnsnames.ora file (on a Windows machine, the file is at %ORACLE_HOME%\network\admin\tnsnames.ora).



You receive the following error: ORA-12705: Cannot access NLS data files or invalid environment specified.

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"

Working with the Java DB (Derby) Database This document demonstrates how to set up a connection to Java DB database in NetBeans IDE. Once a connection is made, you can begin working with the database in the IDE, allowing you to create tables, populate them with data, run SQL statements and queries, and more. The Java DB database is Sun's supported distribution of Apache Derby. Java DB is a fully transactional, secure, standards-based database server, written entirely in Java, and fully supports SQL, JDBC API, and Java EE technology. The Java DB database is packaged with the GlassFish application server, and is included in JDK 6 as well. For more information on Java DB database, consult the official documentation. To follow this tutorial, you need the following software and resources. Software or Resource Version Required NetBeans IDE 7.2, 7.3, 7.4, 8.0, Java EE Java Development Kit (JDK) Version 7 or 8 Java DB version 10.4.x, 10.5.x Note. 

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.

Configuring the Database If you have the GlassFish Server registered in your NetBeans IDE installation, Java DB will already be registered for you. Therefore, you can skip ahead to Starting the Server and Creating a Database. If you downloaded the GlassFish server separately and need help registering it in NetBeans IDE, see Registering a GlassFish Server Instance in the IDE's Help Contents (F1). If you just downloaded Java DB on its own, perform the following steps.

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

The demo subdirectory contains the demonstration programs. The bin subdirectory contains the scripts for executing utilities and setting up the environment. The javadoc subdirectory contains the API documentation that was generated from source code comments. The docs subdirectory contains the Java DB documentation. The lib subdirectory contains the Java DB jar files.

Registering the Database in NetBeans IDE Now that the database is configured, perform the following steps to register Java DB in the IDE. 1. In the Services window, right-click the Java DB Database node and choose Properties to open the Java DB Settings dialog box. 2. For the Java DB Installation text field, enter the path to the Java DB root directory (javadb) that you specified in the previous step. 3. For Database Location, use the default location if a location is already provided. Click OK For example, the default location might look like C:\Documents and Settings\username\.netbeans-derby on a Windows machine.

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

creating, deleting, modifying tables populating tables with data viewing tabular data executing SQL statements and queries

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 (

), signifying that the connection was successful.

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

Using the Create Table Dialog Using the SQL Editor

Using the Create Table Dialog 1. Expand the Contact DB connection node and note that there are several schema subnodes. The app schema is the only schema that applies to this tutorial. Right-click the APP node and choose Set as Default Schema. 2. Expand the APP node and note that there are three subfolders: Tables, Views and Procedures. Right-click the Tables node and choose Create Table to open the Create Table dialog box. 3. In the Table Name text field, type FRIENDS. 4. Click Add Column. The Add Column dialog box appears. 5. For Column Name, enter id. For Data Type, select INTEGER from the drop-down list. 6. Under Constraints, select the Primary Key checkbox to specify that this column is the primary key for your table. All tables found in relational databases must contain a primary key. Note that when you select the Primary 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 are used as the table index. Because all rows must be identified, primary keys cannot contain a Null value.

7. Repeat this procedure now by specifying fields as shown in the table below: Key Index [checked] [checked]

Null [checked] [checked] [checked] [checked] [checked]

Unique Column name [checked] id firstName lastName nickName friendSince email

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 ( ).

Using the SQL Editor: 1. In the Service window, either right-click the Contact DB connection node or the Tables node beneath it and choose Execute Command. A blank canvas opens in the SQL Editor in the main window. 2. Enter the following query in the SQL Editor. This is a table definition for the COLLEAGUES table you are about to create: 3. CREATE TABLE "COLLEAGUES" ( 4. "ID" INTEGER not null primary key, 5. "FIRSTNAME" VARCHAR(30), 6. "LASTNAME" VARCHAR(30), 7. "TITLE" VARCHAR(10), 8. "DEPARTMENT" VARCHAR(20), 9. "EMAIL" VARCHAR(60) ); Note: Statements and queries formed in the SQL Editor are parsed in Structured Query Language. SQL adheres to strict syntax rules which you should be familiar with when working in the IDE's editor. SQL syntax can also

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

Adding Table Data Now that you have created one or more tables in the contact database, you can start populating it with data. There are several ways that you can add records to your table.   

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.

Using the SQL Editor

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

Connecting to a MySQL Database This document demonstrates how to set up a connection to a MySQL database from the NetBeans IDE. Once connected, you can begin working with MySQL in the IDE's Database Explorer by creating new databases and tables, populating tables with data, and running SQL queries on database structures and content. This tutorial is designed for beginners with a basic understanding of database management, who want to apply their knowledge to working with MySQL in NetBeans IDE. MySQL is a popular Open Source relational database management system (RDBMS) commonly used in web applications due to its speed, flexibility and reliability. MySQL employs SQL, or Structured Query Language, for accessing and processing data contained in databases. 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

Java Development Kit (JDK) Version 7 or 8 MySQL database server

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.

Starting the MySQL Server Before you can connect to a MySQL Database Server, you must first ensure that the MySQL Database Server is running on your machine. If the database server is not connected you will see (disconnected) next to the user name in the MySQL Server node in the Service window and you will not be able to expand the node. To connect to the database server, confirm that the MySQL Database Server is running on your machine, right-click the Databases > MySQL Server node in the Services window and choose Connect. You might be prompted to supply a password to connect to the server.

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

Creating Database Tables Now that you have connected to MyNewDatabase, you can begin exploring how to create tables, populate them with data, and modify data maintained in tables. This allows you to take a closer look at the functionality offered by the Database Explorer, as well as NetBeans IDE's support for SQL files. MyNewDatabase is currently empty. In the IDE it is possible to add a database table by either using the Create Table dialog, or by inputting an SQL query and running it directly from the SQL Editor. In the following exercises you will use the SQL editor to create the Counselor table and the Create Table dialog box to create the Subject table. After you create the tables you will run an SQL script to populate the tables. 1. Using the SQL Editor 2. Using the Create Table Dialog Using the SQL Editor In this exercise you will use the SQL editor to create the Counselor table. 1. In the Database Explorer, expand the MyNewDatabase connection node ( ) and note that there are three subfolders: Tables, Views and Procedures. 2. Right-click the Tables folder and choose Execute Command. A blank canvas opens in the SQL Editor in the main window. 3. In the SQL Editor, type in the following query. This is a table definition for the Counselor table you are about to create. 4. CREATE TABLE Counselor ( 5. id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT, 6. firstName VARCHAR (50), 7. nickName VARCHAR (50), 8. lastName VARCHAR (50), 9. telephone VARCHAR (25), 10. email VARCHAR (50),

11. 12.

memberSince DATE DEFAULT '0000-00-00', PRIMARY KEY (id) ); Note: Queries formed in the SQL Editor are parsed in Structured Query Language (SQL). SQL adheres to strict syntax rules which you should be familiar with when working in the IDE's Editor. Upon running a query, feedback from the SQL engine is generated in the Output window indicating whether execution was successful or not.

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 ( ).

Using the Create Table Dialog In this exercise you will use the Create Table dialog box to create the Subject table. 1. 2. 3. 4.

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]

Unique Column Name Data Type Size [checked] id

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.

Running an SQL Script Another way to manage table data in NetBeans IDE is by running an external SQL script directly in the IDE. If you have created an SQL script elsewhere, you can simply open it in NetBeans IDE and run it in the SQL Editor. For demonstrative purposes, download ifpwafcad.sql and save it to a location on your computer. This script creates two tables similar to what you just created above (Counselor and Subject), and immediately populates them with data. Because the script overwrites these tables if they already exist, delete the Counselor and Subject tables now so it becomes obvious that new tables are being created when the script is run. To delete tables: 1. Right-click the Counselor and Subject table nodes in the Database Explorer and choose Delete. 2. Click Yes in the Confirm Object Deletion dialog box. Note that the dialog box lists the tables that will be deleted. When you click Yes in the Confirm Object Deletion dialog box, the table nodes are automatically removed from the Database Explorer. To run the SQL script on MyNewDatabase: 1. Choose File > Open File from the IDE's main menu. In the file browser navigate to the location where you previously saved ifpwafcad.sql and click Open. The script automatically opens in the SQL Editor. 2. Make sure your connection to MyNewDatabase is selected from the Connection drop-down box in the toolbar at the top of the Editor.

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

Creating a Simple Web Application Using a MySQL Database This document describes how to create a simple web application that connects to a MySQL database server. It also covers some basic ideas and technologies in web development, such as JavaServer Pages (JSP), JavaServer Pages Standard Tag Library (JSTL), the Java Database Connectivity (JDBC) API, and two-tier, client-server architecture. This tutorial is designed for beginners who have a basic understanding of web development and are looking to apply their knowledge using a MySQL database. MySQL is a popular open source database management system commonly used in web applications due to its speed, flexibility and reliability. MySQL employs SQL, or Structured Query Language, for accessing and processing data contained in databases. This tutorial is a continuation from the Connecting to a MySQL Database tutorial and assumes that you have already created a MySQL database named MyNewDatabase, which you have registered a connection for in the NetBeans IDE.

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

7.2, 7.3, 7.4, 8.0, Java EE bundle

Java Development Kit (JDK)

version 7 or 8

MySQL database server

5.x

MySQL Connector/J JDBC Driver

version 5.x

GlassFish Server Open Source Edition 3.x or 4.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.

Planning the Structure Simple web applications can be designed using a two-tier architecture, in which a client communicates directly with a server. In this tutorial, a Java web application communicates directly with a MySQL database using the Java Database Connectivity API. Essentially, it is the MySQL Connector/J JDBC Driver that enables communication between the Java code understood by the application server (the GlassFish server), and any content in SQL, the language understood by the database server (MySQL). The application you build in this tutorial involves the creation of two JSP pages. In each of these pages you use HTML and CSS to implement a simple interface, and apply JSTL technology to perform the logic that directly queries the database and inserts the retrieved data into the two pages. The two database tables, Subject and Counselor, are contained in the MySQL database, MyNewDatabase, which you create by completing the Connecting to a MySQL Database tutorial. Consider the following two-tier scenario.

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

Creating a New Project Begin by creating a new Java web project in the IDE: 1. Choose File > New Project (Ctrl-Shift-N; ⌘-Shift-N on Mac) from the main menu. Select the Java Web category, then select Web Application. Click Next.

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

Setting up the welcome page Creating the response page Creating a stylesheet

Setting up the welcome page Confirm that index.jsp is open in the editor. If the file is not already open, double-click index.jsp under the Web Pages node in the IFPWAFCAD project in the Projects window. 1. In the editor, change the text between the tags to: IFPWAFCAD Homepage. 2. Change the text between the tags to: Welcome to IFPWAFCAD, the International Former Professional Wrestlers' Association for Counseling and Development!. 3. Open the IDE's Palette by choosing Window > Palette (Ctrl-Shift-8; ⌘-Shift-8 on Mac) from the main menu. Hover your pointer over the Table icon from the HTML category and note that the default code snippet for the item displays.

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

The HTML table code is generated and added to your page. 6. Add the following content to the table heading and the cell of the first table row (new content shown in bold): IFPWAFCAD offers expert counseling in a wide range of fields. To view the contact details of an IFPWAFCAD certified former professional wrestler in your area, select a subject below: 7. For the bottom row of the table, insert an HTML form. To do so, place your cursor between the second pair of tags, then double-click the HTML form ( ) icon in the Palette. In the Insert Form dialog, type in response.jsp in the Action text field, then click OK.

8. Type in the following content between the tags (new content shown in bold):

Select a subject: 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: Welcome to IFPWAFCAD, the International Former Professional Wrestlers' Association for Counseling and Development! IFPWAFCAD offers expert counseling in a wide range of fields. To view the contact details of an IFPWAFCAD certified former professional wrestler in your area, select a subject below: Select a subject: 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.

Creating the response page In order to prepare the interface for response.jsp you must first create the file in your project. Note that most of the content that displays in this page is generated dynamically using JSP technology. Therefore, in the following steps you add placeholders which you will later substitute for the JSP code. 1. Right-click the IFPWAFCAD project node in the Projects window and choose New > JSP. The New JSP File dialog opens. 2. In the JSP File Name field, enter response. Note that Web Pages is currently selected for the Location field, meaning that the file will be created in the project's web directory. This is the same location as where the index.jsp welcome page resides. 3. Accept any other default settings and click Finish. A template for the new response.jsp page is generated and opens in the editor. A new JSP node also displays under Web Pages in the Projects window.

4. In the editor, change the title to: IFPWAFCAD - {placeholder}. 5. Remove the Hello World! line between the tags, then copy and paste the following HTML table into the body of the page: {placeholder} Description: {placeholder} Counselor: {placeholder} member since: {placeholder}

Contact Details: email: {placeholder} phone: {placeholder} 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;

border-bottom: 1px solid; } td { padding: 10px; } a:link { color: #be7429; font-weight: normal; text-decoration: none; } a:link:hover { color: #be7429; font-weight: normal; text-decoration: underline; } 4. Link the stylesheet to index.jsp and response.jsp. In both pages, add the following line between the tags: To quickly navigate between files that are open in the editor, press Ctrl-Tab, then select the file you are wanting.

Preparing Communication between the Application and Database The most efficient way to implement communication between the server and database is to set up a database connection pool. Creating a new connection for each client request can be very time-consuming, especially for applications that continuously receive a large number of requests. To remedy this, numerous connections are created and maintained in a connection pool. Any incoming requests that require access to the application's data layer use an already-created connection from the pool. Likewise, when a request is completed, the connection is not closed down, but returned to the pool. After preparing the data source and connection pool for the server, you then need to instruct the application to use the data source. This is typically done by creating an entry in the application's web.xml deployment descriptor. Finally, you need to ensure that the database driver (MySQL Connector/J JDBC Driver) is accessible to the server. Important: From this point forward, you need you ensure that you have a MySQL database instance named MyNewDatabase set up that contains sample data provided in ifpwafcad.sql. This SQL file creates two tables, Subject and Counselor, then populates them with sample data. If you have not already done this, or if you need help with this task, see Connecting to a MySQL Database before proceeding further. Also, your database needs to be password-protected to create a data source and work with the GlassFish server in this tutorial. If you are using the default MySQL root account with an empty password, you can set the password from a command-line prompt. This tutorial uses nbuser as an example password. 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.

1. Setting up a JDBC data source and connection pool 2. Referencing the data source from the application 3. Adding the database driver's JAR file to the server Setting up a JDBC data source and connection pool The GlassFish Server Open Source Edition contains Database Connection Pooling (DBCP) libraries that provide connection pooling functionality in a way that is transparent to you as a developer. To take advantage of this, you need to configure a JDBC (Java Database Connectivity) data source for the server which your application can use for connection pooling. For more information on JDBC technology, see The Java Tutorials: JDBC Basics. You could configure the data source directly within the GlassFish server Admin Console, or, as described below, you can declare the resources that your application needs in a glassfish-resources.xml file. When the application is deployed, the server reads in the resource declarations, and creates the necessary resources. The following steps demonstrate how to declare a connection pool, and a data source that relies on the connection pool. The NetBeans JDBC Resource wizard allows you to perform both actions. 1. Open the New File wizard by pressing the New File ( ) button in the IDE's main toolbar. Select the GlassFish server category, then select JDBC Resource and click Next. 2. In step 2, General Attributes, choose the Create New JDBC Connection Pool option, then in the JNDI Name text field, type in jdbc/IFPWAFCAD.

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

Referencing the data source from the application You need to reference the JDBC resource you just configured from the web application. To do so, you can create an entry in the application's web.xml deployment descriptor. Deployment descriptors are XML-based text files that contain information describing how an application is to be deployed to a specific environment. For example, they are normally used to specify application context parameters and behavioral patterns, security settings, as well as mappings for servlets, filters and listeners. Note. If you specified Java EE 6 or Java EE 7 as the Java version when you created the project, you need to create the deployment descriptor file by choosing Web > Standard Deployment Descriptor in the New File wizard. Perform the following steps to reference the data source in the application's deployment descriptor. 1. In the Projects window, expand the Configuration Files folder and double-click web.xml to open the file in the editor. 2. Click the References tab located along the top of the editor. 3. Expand the Resource References heading and click Add to open the Add Resource Reference dialog. 4. For Resource Name, enter the resource name that you gave when configuring the data source for the server above (jdbc/IFPWAFCAD). 5. Type javax.sql.ConnectionPoolDataSource in the Resource Type field. Click OK. The Description field is optional, but you can enter a human-readable description of the resource, e.g., Database for IFPWAFCAD application.

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 tags are now included. Database for IFPWAFCAD application jdbc/IFPWAFCAD

javax.sql.ConnectionPoolDataSource Container Shareable 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.

Adding Dynamic Logic Returning to the index.jsp and response.jsp placeholders that you created earlier in the tutorial, you can now implement the JSTL code that enables pages to generate content dynamically, i.e., based on user input. To do so, perform the following three tasks. 1. Add the JSTL library to the project's classpath 2. Implement JSTL code Adding the JSTL library to the project's classpath You can apply the JavaServer Pages Standard Tag Library (JSTL) to access and display data taken from the database. The GlassFish server includes the JSTL library by default. You can verify this by expanding the GlassFish Server node under the Libraries node in the Projects window, and searching for the javax.servlet.jsp.jstl.jar library. (Older versions of the GlassFish server use the jstl-impl.jar library.) Because the GlassFish server libraries are by default added to your project's classpath, you do not have to perform any steps for this task. JSTL provides the following four basic areas of functionality.    

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 tag to create an SQL query, then it uses the tag to loop through the query's resultset and output the retrieved data. 2. Place your cursor above the 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.) SELECT subject_id, name FROM Subject

Note that the IDE automatically added taglib directives needed for the JSTL tags used in the generated content ( and ). 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 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 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). Select a subject: An alternative, simpler way to integrate the tags into the HTML form would be as follows. Select a subject: ${row.name}

In either case, the tags loop through all subject_id and name values from the SQL query, and insert each pair into the HTML tags. In this manner, the form's drop-down list is populated with data. 7. Delete the table that was generated from the DB Report item. (Deletion shown below as strike-through text.) SELECT subject_id, name FROM Subject 8. Save your changes (Ctrl-S; ⌘-S on Mac). 9. Refresh the welcome page of the project in your browser. Note that the drop-down list in the browser now contains subject names that were retrieved from the database. You do not need to redeploy your project because compile-on-save is enabled for your project by default. This means that when you modify and save a file, the file is automatically compiled and deployed and you do not need to recompile the entire project. You can enable and disable compile-on-save for your project in the Compiling category of the Properties window of the project. response.jsp The response page provides details for the counselor who corresponds to the subject chosen in the welcome page. The query you create must select the counselor record whose counselor_id matches the counselor_idfk from the selected subject record. 1. Place your cursor above the declaration (line 7), and double-click DB Query in the Palette to open the Insert DB Query dialog box. 2. Enter the following details in the Insert DB Query dialog box.

o o o o

Variable Name: counselorQuery Scope: page Data Source: jdbc/IFPWAFCAD Query Statement: SELECT * FROM Subject, Counselor WHERE Counselor.counselor_id = Subject.counselor_idfk AND Subject.subject_id = ?

3. Click OK. The following content is generated in the response.jsp file. (New content shown in bold.) SELECT * FROM Subject, Counselor WHERE Counselor.counselor_id = Subject.counselor_idfk AND Subject.subject_id = ? Note that the IDE automatically added the taglib directive needed for the tag. Also, note that you used an 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 tag so that it can be used in place of the SQL question mark (?) during runtime. 4. Use a 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.) SELECT * FROM Subject, Counselor WHERE Counselor.counselor_id = Subject.counselor_idfk AND Subject.subject_id = ?

Although the resultset returned from the query should only contain a single record, this is a necessary step because the page needs to access values from the record using EL (Expression Language) statements. Recall that in index.jsp, you were able to access values from the resultset simply by using a tag. However, the tag operates by setting a variable for the rows contained in the query, thus enabling you to extract values by including the row variable in EL statements. 5. Add the taglib directive for the JSTL core library to the top of the file, so that the tag is understood. (New content shown in bold.) 6. 7. In the HTML markup, replace all placeholders with EL statements code that display the data held in the counselorDetails variable. (Changes below shown in bold): ${counselorDetails.name} ${counselorDetails.name} Description: ${counselorDetails.description} Counselor: ${counselorDetails.first_name} ${counselorDetails.nick_name} ${counselorDetails.last_name} member since: ${counselorDetails.member_since} Contact Details: email: ${counselorDetails.email} phone: ${counselorDetails.telephone}

Running the Completed Application You've now completed the application. Try running it again to see how it displays in a browser. Note that because of NetBeans' Compile on Save feature, you do not need to worry about compiling or redeploying the application. When you run a project, you can be sure the deployment contains your latest changes. Click the Run Project (

) 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.     

Do database resources exist? Do the connection pool and data source exist on the server? Is the MySQL Connector/J driver accessible to the GlassFish server? Is the database password-protected? Are the connection pool properties correctly set?

Do database resources exist? Use the IDE's Services window (Ctrl-5; ⌘-5 on Mac) to ensure that the MySQL server is running, and that MyNewDatabase is accessible and contains appropriate table data.  

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.

Do the connection pool and data source exist on the server? After deploying the application to the GlassFish server, the glassfish-resources.xml contained in the project should instruct the server to create a JDBC resource and connection pool. You can determine whether these exist from the Servers node in the Services window. 

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

Is the MySQL Connector/J driver accessible to the GlassFish server? Make sure that the MySQL Connector/J driver has been deployed to the GlassFish server. (This is discussed in Adding the database driver's JAR file to the server.) 

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.

Is the database password-protected? The database needs to be password-protected to enable the GlassFish server data source to work properly in this tutorial. If you are using the default MySQL root account with an empty password, you can set the password from a command-line prompt.    

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.

Are the connection pool properties correctly set? Ensure that the connection pool is working correctly for the server. 1. Open the Services window (Ctrl-5; ⌘-5 on Mac) and expand the Servers node. 2. Right-click the GlassFish server node and choose View Admin Console. 3. Enter the username and password if you are prompted. You can view the username and password in the Servers manager. 4. In the tree on the left side of the console, expand the Resources > JDBC > JDBC Connection Pools > IfpwafcadPool node. Details for the IfpwafcadPool connection pool display in the main window. 5. Click the Ping button. If the connection pool is set up correctly, you will see a 'Ping Succeeded' message.

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

Starting the Download Starting the Installation See Also

Starting the Download 1. Go to http://dev.mysql.com/downloads/installer/. 2. Click the Download button. 3. Save the installer file to your system. top Starting the Installation After the download completes, run the installer as follows: 1. Right-click the downloaded installation file (for example, mysql-installer-community-5.6.14.0.msi) and click Run. The MySQL Installer starts. 2. On the Welcome panel, select Install MySQL Products.

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.

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF