You are on page 1of 16
‘Working with the Java DB (Derby) Database This document demonstrates how to setup a connecton fo Java DB dalabase in NetSeans IDE. Once a eannecton is made, you can begin working wih the database inte IDE. allowing yout ce fables, populate them th data run SOL statements and queries, ans more, The Java DB database s Sur's suppored alstibuton of Apache Derby. Java DBs a filly vansactonal, secure, standards-based database server. writen enrol in Java, and Rly supports SQL, JDBC API, and Java EE technology. The Java DE database is packaged with he (lasaFisn application server, andi incuded In JOK 6 as well For mae ntomation an Java DB database, consult te ofa documentation. Contents + Configuring the Database + Registering te Database in NetBeans DE + Staring ie Server and Creatng a Dalavase + Connecting othe Database + Creating Tables + Adding Table Data + Deleting Tables + Using an Extemal SOL Sept + Reereatng Tables oma Diferent Database + Seealso ‘Toolow this tutorial, you need the folowing software and resources ‘Sottware.orResource Version Required NetBeans IDE 72,73.74,80,Javaee Java Development Kt(JOX) Version 7 oF 8 Java 08 version 104%, 105 + Java D8 is installed when you install JK 7 or JOK 8 (excepton Mac OS X.Iyou are using Ma OS X you can downloae and install Java 0 manusalyoruse the Java thats installed by Java EE version of he NetBeans IDE installer. Configuring the Database Ityou nave the GlassFish Server rgisteredin your NetBeans IDE instalation, Ja ahead to Staring he Server and Creating a Database, _DB.wil aeady be registred fr you. Therefore, you can skip Ityou dowloaded the GlassFish srver separately and need help regstorng tin NetBeans IDE, soe Registering a GlassFish Server Instance In the DES Help Contents (1). you just downloaded Java 08 on ts own, perform the folowing stops. Run the settentracing fe. A oldernamed add vlbe crest in the same locaton ashe Sl. yo ust downloaded Java D8 and wanttohave the database server reside ina diferentocaton than where twas exacted to, you shoul elocateitnow. 2, Onyour system, create anew directory tobe used asa nome atector forte individual instances ofthe database server. For example, you can creae this folder in the Java DB ret lrecinr Gavad)orin any oer locaton Before continuing further, Ls important to understand te components found in Java D3 ool rectory: + The dene subsirecory contains the demonstration programs. +The bin subtrecory contains he seit for executng utiles and seting up the environment +The Javadoc subdirectory conlans he API documentaon hal was genetaed lm source code comments + The doce subsirectry contains the Java DB documentaton +The 1 Lp subarectory contains the Java DBar les Registering the Database in NetBeans IDE Is configured, perform the folowing steps to register Java DB inte IDE, 1. inthe Senices window, right-clk the Java D8 Database nade and choose Properies to open the Java OB Setings dialog box 2. Forthe Java 08 instalation text fla, enter the path othe Jave D8 rood retary Yavadb) mat you specited inthe previous ste. 2, For Database Location, use the dfaullacaton if location sready provided. Clik OK For example, the default location mighlook Ike C:\Documents and Settings\usornane\.netbeans-derby on a Windows O00 _________ Soon D0 Properties ‘Specify the folder where Java DB is installed and the folder where you will keep your databases, The database location folder wil be used asthe value of the Serby.system home property. Java DB Installation: ons/NetOeans/slassfish- T22/javadb oat econ Cnet) oD [Note he Database Location Seld is empty youl need to st he pat othe directory hat contains your databases. You wil eed to create airecory forthe databases itna director exis. Starting the Server and Creating a Database ‘ne Java DB Database menu options are payed when you rght ak he Java DB nde inthe Sences window. Tis context menuitem alow you'o slaLand slop he databace server, create anew dalabase sance as wells epaterdalabase servers in he IDE (as demonsvaledin the previous stp), To late database sever 1. inthe Senioes window, rightclick the Java OB node and choose Start Serer, Note he following ouputin the Output window. ncatng thatthe server has sated Saag 2, Right-click ne Java D8 node ana choose Crea Database to open the Create Java DB Dalabase alg 23. Type contact forthe Database Name. 4. Type nbusor forthe User Name and Password. Clek OK: Database Name: [contact User Name: nbuser Password: Confirm Password Database Location: /Users nb/.netbeans-derby (Properties...) Cnet) OD ‘Note. The Database Locations the dau location set during instaation af Java DB tom GlassFish. you instal Java 08 separately, hs locaton mightbe diferent ‘Ator you create the database, you expand te Dalabases node inthe Services window you cans conection and tha the dalaoase was ade fhe Ist unde he Java OB noe, shat he IDE coated a datanace Connecting to the Database So ar, you have suocesstly stared he he database server and created a database instance named contact in the IDE. hte Sences ‘window ofthe IDE you can perform the foloweng common a5 on data + ezeatng, deleting, mectving tables + populating tables wih data “+ wowing tabular data + executing SAL statements and quenies In oderta begin working with te contact dalabase, you need fo rea # connection Ii, To connectto Be contact database perform he ‘allowing steps. 1. Expand the Databases node in re Services window and locate the new database and he dalabase camnecton nodes, ‘The database conection node( i ie aaplayes under the Databases node. The name oftedattbase Is leplayed under he Java DB rode, [fies [Favors [Sewiees YS Databases > if ys. server at ocanost 3306 (rot (isconected) y ( Javave © book © ardanbase S chapteris08 B consut S comact S sample 1S sun-appsere-sampies S wave Su [nbuser on NBUSERI » 6] Jdbe-deroy.//locahost:1527/sample {app on APP] {Web Services LB Servers (Gh Maven Repostories ous 'W Hudson Builders (G Issue Trackers Note. Youwil ako see he sample [app cx APP) dalabase connecton thats he default database schema. 2. Rightlik he contact database connection node (jabe:derby://Localhost :1527/eontact (nbuser on NBUSER)) and choose Connect ‘The connecton nade con appears whole (EE, signing that he connocton was success 1, Create a convenientleplay name forthe database by right-ckng the database connection nods (Gdberderny://Lecalhost:1527/contact (nbuser on NBUSER)) and choosing Rename. Type Contact 08 nthe ox. {eld and eck OK Creating Tables The contact database that you ust reales curently empyItdoes not yt contin any tables or dalam NetBeans IDE you can add a database table by ether using te Create Table dialog, or by inputing an SQL statementand running tart fom the SOL Ealor. You can explore bath metho: + Using the Create Table Diaiog + Using the SOL Esttor Using the Create Table Dialog 1. Expandihe contact BB conection node and note Bat there are several schema eubnodes. The app schemas the only schema ‘at applies ois tutorial. Righ-lek the APP node and choose Set as Defautt Scvema, 2, Expand the APP node and note that here are tree subfolders: Tales, Views and Procedures, Right-click ne Tables nade ang ‘choose Create Table to open the Create Table dialog box. 8 Inthe Table Name text fald, ype PRTENDS. 4, Click Add Column, The Add Column dialog box appears. '5. For Column Name, enter‘ For Osta Type, select INTEGER tom he drop-down ist 8. Under Constraints, select the Primary Key checkbox o speci thal this column the pray key for your table Al ables found in Felatonal databases most contain primary key. Note that when you select he Primary Key check ox, the Index and Unique cveck boxes ae also automatically selected ard the Nullcheck boxe deselecid,This's because primary keys are used fo ienty a unique own the eatsbace, and by default are used asthe table index, Because al ows musi be dened, primary keys cannot coniaina Wel vale, Default: Constraints GB Primary key AB unique Null VY index Cnc) GOD 7. Repeat is procedure now by speciving feds as shown inthe tale below: 8 Key Index Null Unique Column name Detatype Size [enecked) (cnecked] leneckea) 1s INTEGER 0 [oneckea} frstlame VARCHAR 20 leneekea} Jasname VARCHAR 20 Icheckes} ricktlame VARCHAR 30 (checkes} iendsince DATE 0 [oneckes} emai! VARCHAR 60 You te cresting a able named FRIENDS that holds he fllowing dat for enen contac record First Name LastName Nick Name Feiand Since Date EmaltAddross ‘Table name: FRIENDS 8. When you ate sure that your Create Table aislog contains the same specications ros the ERZENDS table in he database, and you can Cree) Cane) Go move shown above, clck OK. The DE 1 anew FRIEND lable node (EN) apa uncer ne Tables nooo. Beneath he able node the clus (elds) ae Iisted, stating wih tre primary Key A, Using the SQL Editor: 1. Inthe Sonvice window, etherrightclckthe Contact 08 connection nade or the Tables nods bon Command, A blank canvas opens inte SOL Edo in te main window. 2. Entorthe following query inte SOL Eaior. This is table dofiniton fer the COLLEAGUES taole you are aboutio create: CREATE TABLE "COLLEAGUES" ¢ sr" INTEGER not null primary key, FIRSTUAME™ VARCHAR (30) , “LASTNAME” VARCIIAR(30), SEETLE" VARCHAR(10;, “oEeARIMEN?" VARCHAR (20), “EMATL" VARCHAR 60) Noe: Statements and queries formed in the SAL. Editor are parsed in Stuchired Guery Language, SOL adheres fo bic syntax rules wrich you shoule be ‘amir wih when working in the IE's edt. SOL syriax can alto dfer depending on the dataase ‘management system. See the JavaD8 Reference Manual fr specif guidelines. 8. Cliche Run SaL {Dy buton nthe askbar att top oF te editor (CH-Shit-) to exncut the query. I Bie Output window (Ct). a message dspays ndeating that he statement was success executed Executed eucce Zine 1, column 1 ily in 0.162 s, 0 rows affected. Execution finished after 0.162 2, 0 error(s) occurred. 4. Toverly changes, right-click he Contact. B cannecton node inthe Services window and choose Retesh. This updates he untme Uteompanent the curent status of he specited database. Ths slaps necessary wnen running queries fam he SQL, Editor in NetBeans IDE Note hat he new COLLEAGUES table node (now daplaye under Tales inthe Snes window. Adding Table Data ‘Now that you have created one or more lablesin he conta: can 2d records to your table latabase, you can sta populating itty data, There are several ways that you + Wile an SAL statementin the SAL Ealtor nat supolesa value fr every Feld presentin the table schema + Use the SOL Editor toad ecards tote fable + Use an extemal Sa: scnptto import records tthe table. Read the sectors below to leam how to use all hese methods ofpopulaing he FRTENDS table with data Running an SQL Statement + Expand ne Tables under he Cont.act DB node in he Services window, rightclick the FRIENDS lable and choose Execute Command to open he SOL Esti window. 2, Inthe SOL Esitor enter the fllowing latement. INSERT INTO APP-PRIENDS VALUES (1, "Theodore", ‘Bagwell, "T-Bag!, "2004-12- 25%, "thagetoxriver.com') ‘while you are typing, you can use the SAL Editor code completion. ‘5. Rightelk inside he SOL. Eltor and choose Run Statement. The Output window dsplays a message IndleangHelthe statement was successtly executed 4, To werly hat ne new record nas been added to the FRIENDS lable, ight-clck he FRIENDS table node in he Services window and choose View Data, ‘wtien you choose View Data, a query to Selecta he data rom he table fs automaticaly generates inte upper pane ofthe SAL. Eitr. ‘The results ofthe statement are coplayedin he lower pane of he SOL Eaton his case, he FRIENDS table dlsplaysin he lower pane.Note fat anew row has been added wit the data you jst supplie rom he SQL statement Using the SQL Editor 1 Rigntelckthe ERZENDS table node and choose View Dats (you have not done isa the as stop ofthe previous section). 2, Cickthe hsert Records) (A2t-1) button o add arom. ‘The Insert Records dialog box appears 43. Clickin each cell and enter records, Note hat forte cells with Date data ype, you can choose a dae fom the calendar. Click OK when youare dove. Press CTRL Tab to exit dtaenty mode from the table. Press CTAL+0 to set NULL value and CTRL+1 to ‘Set DEFAULT value fora given column. FamENce ‘auc [2012-07-16 Sun Mon Tue Wed Thu fri_sat Larasnaiaieeesera| soon Rew j | fi 7 we 9 20 21 | | t 2B M4 % F 2 29 30 | Todays 16)uiy2012 | In the SOL Ealitr, you can sorte results by clicking ona row header, mil and delete existing records, and see be SQL script forthe ‘actions you are doing inthe elor (he Show SOL Seip command om the pop-up menu). Deleting Tables Inte following step, you use an extemal SOL spt reale a new COLLEAGUES table However, you st created COLLEAGUES table inthe Using te SO Eder secon above. In order to maka iter thal ho SOL seiptindasd creates a now ‘ble you can delat the already created (COLLEAGUES lable now. To dlele a database table perorm the allowing steps. 1 Expand the Tables node under tre database conrecton node inthe Services window. 2, Right-click he table hat you wantto delete and choose Dele. Using an External SQL Script Issulpg commands om an extemal SOL. scripts a popular way to manage your database. You may have aready created an SOL sept clsewnere, and want impetitinto NetBeans IDE te run ton a spect database. In tis exercise the seri wll create a new able named COLLEAGUES and populate wih daa. Perform the following steps to run he script on the contact database, + Download colleagues to your toca system 2. Choose File > Open File rom te IDEs main menu nthe Sle browser navigate to fe locaton ofthe saved colLeagues..s@l tle and ‘lek Open. The srptaulomataly apensin Re SAL. Eator. ‘Alwmatively, you can copy the contents of sleagues.sal and then open the SOL dior and paste the contents of SAL salir Aleints he 1, Make sure your connection to Contact. D8 se elected fom te Connection drop-down box the tel bar atthe tap ofthe ectr. nating 4. Click tne Run Sax (EB; buton inne SaL Editor's task bar. Th soiptis executed againstthe selected database, and any feedback's ‘generated n te Output window. 5, Towerly changes, ight-c he Contact 08. connecton node inthe Services window ané choose Refresh. Note at the new [COLLEAGUES table fom te SOL senpt rw displays as a able nade under contact in he Serices window, 68, Towew the data contained in fe new ables, rghtcick he COLLEAGUES lable and choose View Data. In this manner, youcan also eampare the tabula’ data wih the data contained in the SOL. sept to see that hey mate. Recreating Tables from a Different Database you have a table tom another daiabase which you would tke to eereste inthe tabase you ae working n fom NetBeans IDE, the IDE ofers 1a handy ofr this. You frst need to have the second database registred inthe IDE similar io what was described athe beg nning ofthis luloral Forte purposes of i utr, use the sample dalabase thal comes packaged wit Java DB. Tis processis essentially cared outin {wo parts: You fst 'cab'the table deSniion ofthe select table, the you can recreate the ible in your chosen database: + Connect the sample database by righteleking the connection node under the Databases node Inte Services window and choosing Connect (usemame and passwords app) 2. Expand he Tables node under he sample database connesction, ghclck he CUSTOMER lable node and choose Grab Structure saeaO) © stbases > (i Mysal Server at locathost:3306 [root] (disconnected) > ia ae » Gi Deve > El conacron y EB) jdbc:derby.//locathost:1527 /sample [app on APP) va ¥ ot rabies 8 8 View Data manent Execute Command.. Sw ‘Add Column rates Refresh. Delete > Recreate Table. Meee ee ;G00am! Properties i ein 3. Inthe Grab Table dialog hat opens, specily a locafon on your compute to save the grab fle that will created. Click Save. The grb le records he table detrion ofthe selecied table 4. Expand the APP schema node under open the Recreate Table dlog box. Contact D8 database connection, rightclick ne Tables node and choose Recreate Table to ‘5. nthe Recreate Table dialog box, navigate to the locaton were you saved the CUSTOMER grab fle and lick Open o open the Name the ‘Table dlalog box. Se Create table script ‘create table "APP*.CUSTOMER ( ‘CUSTOMER ID INTEGER not null primary key, DISCOUNT_CODE CHAR() not null, ZIP VARCHAR(10) not null, NAME VARCHAR(30), ‘ADDRESSLINE] VARCHARGO), 'ADDRESSLINE2 VARCHAR(3O), CITY VARCHAR@S), ‘STATE CHARQ), PHONE CHARQ2), FAX CHARG2), EMAIL VARCHAR(AO), ‘CREDIT_LIMIT INTEGER 6, Athis pointyou can change the table name o edithe table defnifon. Otherwise, lick OK to immesditaly create the able inthe contact database. Anew CUSTOMER ible node appears beneath the Cont.act DB connecton node. Projecs | Fes | Favorites [Services = Databases (MySQL Server at locathost:3306 (root (disconnected) (Java D8 Gowers El contact 08 Ifyou vew te data ine new CUSTOMER able You Wil ee thal ere are no recor in he database, bul at he sbuce of he table dental tthe table hat you grabbes. ‘Send Us Your Feeaback See Also ‘This conctudes te Working wth he Java 08 (Derby) Database tla. Ths ural demonstates how to setup & connecson to he Java OB database n NetBeans IDE. ten demanstated howto eats, ew, modiy and delete tables n the IDEs Services window. Naso showed now work wth he SOL Etor oad data to tables, and use the IDEs funcional allowing youto recreate tables using defritons om othor databases. Forrelatod and more advanced tutorials, se te following resources: ‘+ Connecting to a MySOL Database, Demonstrates haw to conigure and connectto a MySQL database in NetBeans DE, + Creating a Simple Web Apolicaion Using a MySQL Database. Demonstrates haw fo create a simple web application at connects ‘0 8 MySQL database sore ‘+ Notaeans Platform GRUD Application Tutorial. Demonsrates how intagrate a Java DB database into @ NelBeans Patorm application

You might also like