This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
DB2 Developer Workbench, Part 3: DeveloperWorkbench and XMLBasic tasks
Skill Level: Intermediate
Debra R. Eaton ([email protected])DB2 Software Information Technology SpecialistIBM
19 Oct 2006
The IBM® DB2® Developer Workbench (DWB) provides out-of-the-box integrateddevelopment for DB2 9 pureXML. DWB is based on the Eclipse open sourceIntegrated Development Environment (IDE). Learn how the DWB resources,perspectives, views, editors, and wizards assist you to work with the XMLfunctionality in DWB.
Section 1. Before you start
About this tutorial
This tutorial takes a basic approach to working with XML in the DWB Eclipseenvironment, starting by creating an XML table, schema and document, followed byquerying XML data with a stored procedure.
Objectives
• Learn how the DWB resources, perspectives, views, editors, and wizardsassist you to work with XML.
• Become familiar with tasks such as creating, registering, and editing XMLschemas, creating XML instance documents from schemas, creatingXML-related database objects such as tables that contain XML data
You must install and configure the SAMPLE database that is included with DB2 9.1.See the DB2 product documentation and First Steps for more information. Ensurethe SAMPLE database is XML-enabled by specifying the XML option at databasecreation.
See Resources for links to install DB2 and the Developer Workbench.
System requirements
To run the examples in this tutorial, you need to install DB2 9.1 and the SAMPLEdatabase. You must be able to connect to the SAMPLE database with a user ID andpassword.
The schema used throughout this tutorial is DEATON. Replace the DEATONschema with your schema, represented in the instructions by SCHEMANAME, whena task requires a schema name.
Section 2. Set up the Data perspective
Introduction
This section steps you through the initial tasks of working with the Data perspectivein DWB. In this section, accomplish the following tasks:
• Start DWB
• Verify the Data perspective
• Connect to a database
• Create a data development project
Start DWB
From the Windows desktop, select Start > All Programs > IBM DB2 DeveloperWorkbench > DB2 Developer Workbench 9.1 > DB2 Developer Workbench.Click OK to pick the default location. After you choose the workspace location, asingle Workbench window displays. A Workbench window offers one or more
Note: The first time the workspace is used, the DWB welcome screen is displayed.You then have to click on the arrow in the upper, right-hand corner (the Workbenchlink) to get to the Workbench, where you are shown the Data perspective. You canlaunch this welcome page using the help menu.
Figure 1. Start DWB
Verify the Data perspective
DWB opens by default in the Data perspective. Data will appear on the title bar inthe upper left. The Data icon will be indented on the icon bar in the upper right.
DWB lists all known database connections in the Database Explorer view.Right-click the SAMPLE database connection in the Database Explorer Connectionsfolder, and select Reconnect from the context menu.
Note: You can create more database connections that the DB2 server does notknow about with the Create Connection wizard.
.Figure 3. New connection
In the Database Authorization window, enter your database user ID and password.Select OK.
Figure 4. Database authorization
Create a project
In the Data Project Explorer view, right-click on the white space within the view.Select New >Project. The New Data Development Project wizard will open.
Specify the JDK home directory in the JDK home text box, and click Finish. Thedata development project called XMLBasic is displayed in the Data Project Explorerview.
You can create a table in DWB with the SQL editor. In this section, accomplish thefollowing tasks:
• Create table XMLSAMPLE in the SAMPLE database
• Define column DOC as an XML data type
Create a table
In the Database Explorer view, expand the SAMPLE database schema tree.Right-click the Tables node. Select New > With SQL Editor to launch the SQLEditor.
Figure 10. Launch SQL Editor
In the SQL Editor, enter the CREATE TABLE statement to create a table calledXMLSample, which includes one XML column called doc. Add a DROP TABLEstatement to remove a previous version of XMLSample.
Click the Save icon on the task bar. In the Save As window, select the XMLBasicparent folder. Type create XMLSample.sql in the File Name text box. Click OK.
Figure 12. Save create XMLSample.sql script
In the Data Project Explorer view, in the XMLBasic project SQL Scripts folder, selectthe script create XMLSample.sql. Right-click on it, and select Run SQL.
On the Data Output view, verify the script create XMLSample.sql ran successfully.You should see Status = Success, Action = Run, and Object Name = SQL Editor. Inthe Messages tab, you should see the message Run Successful. On theDatabase Explorer view, right-click the SAMPLE node. Select Refresh. Expand theSAMPLE database schema tree. Verify the XMLSample table exists in the Tablesnode.
Figure 14. SELECT
Section 4. Create an XML schema
Introduction
You can create an XML schema in DWB with the XML Schema Editor. The XMLSchema Editor has two views: the Source view shows the schema source codeinside a text editor, and the Graph view shows a graphical representation of theschema. Tabs at the bottom of the XML Schema Editor enable switching betweenthe two views. In the Graph view, add new global elements and attributes with thecontext menu options. Drill down into element hierarchies by double clicking on theelement. The context menu adds and modifies elements in the XML schemastructure.
• Define a complex type element called CUSTOMERINFO
• Define an element sequence consisting of NAME, CITY, and ZIP inCUSTOMERINFO
Create a schema
In the Data Project Explorer view, expand the XMLBasic project tree. Right-click theXML Schema Documents node. Select New to launch the Create XML Schemawizard.
Figure 15. Launch the Create XML Schema wizard
In the New XML Schema window, select the XMLBasic parent folder. TypeSampleSchema.xsd in the File Name text box. Click Finish.
In the XML Schema Editor, select the Graph tab at the bottom of the editor to switchto the graphical view of the XML Schema. Right-click the white space in the Elementpane. Select Add Element.
Figure 17. Add an element in the XML Schema Editor
Add the element City and Zip to the customerinfo type using the same process aswhen you added Name. Verify the elements in the XML Schema Editor graphicalview and the Outline view.
Figure 22. Verify elements in the XML schema graphical view and Outline view
Select the Source tab in the XML Schema Editor. Find the customerinfo, Name,City, and Zip elements in the schema.
Figure 23. Verify the XML schema in the XML Schema Editor
You can register an XML schema to the XML Schema Repository with the DWBRegister XML Schema Wizard. XML schemas need to be registered in the XMLSchema Repository (XSR) so the database can decompose (shred) and validateXML data. A user can manage XML schema documents and XML schemas in theXSR by viewing their properties and dropping them from the server when they areno longer needed.
In order to register an XML schema, you must have all the documents in yourproject. For multi-document schemas with dependencies, the schema location in thedocuments must be the filename of the documents.
You can use registered XML schemas to perform validation testing in the TableEditor. When you insert or modify a value for an XML column, you can specify thatthe document is to be validated, either based on information in the document thatindicates the schema which it conforms to, or a schema specified by the user.
In this section, accomplish the following task:
• Register SAMPLESCHEMA in the SAMPLE schema repository
In the Data Project Explorer view, expand the XMLBasic project tree. Right-click theSampleSchema node. Select Register an XML Schema wizard to launch theRegister XML Schema wizard.
Figure 25. Launch the Register XML Schema Wizard
In the Relational Schema Name and XML Schema window, select the DEATONrelational schema name. Type SampleSchema in the XML Schema Name text box.Click Next.
Figure 26. Relational Schema Name and XML Schema Name
should see Status = Success, Action = Register, and Object Name =SAMPLESCHEMA. In the Messages tab, you should see the message RegisterSuccessful. On the Database Explorer view, right-click the SAMPLE node. SelectRefresh. Expand the SAMPLE database schema tree. Verify the SAMPLESCHEMAexists in the XML Schemas node.
Section 6. Generate an XML document from an XMLschema
Introduction
Use the Navigator View to generate a sample XML document from an XML schema.In this section, accomplish the following task:
• Generate XML document SAMPLESCHEMA.xml
Generate an XML document from an XML schema
Select the workbench window menu options Window > Show View > Navigator. Ifthe Navigator view opens in the bottom, right area of DWB, drag the Navigatorwindow on to the Data Project Explorer window.
In the Navigator view, expand the XMLBasic project tree. Right-clickSampleSchema.xsd. Select Generate > XML File to launch the Create XML filedialog. Click Next.
Select customerinfo in the root element dropdown list. Click Finish. ASampleSchema.xml file is generated from the SampleSchema.xsd file. TheSampleSchema.xml file opens in the XML editor in the Source view, which consistsof a text editor with color coding.
In the XML Editor, select the Design tab to switch to the graphical view of theSampleSchema.xml document hierarchy.
Note: You can launch the XML Editor by opening the Navigator view, right-clickingon the XML file, and selecting Open With > XML Editor.
Figure 32. XML Editor Source view of an XML document
In the Design view of the XML Editor, expand the customerinfo element. Select theName value in the grid box next to the Name element. Enter Smith. Select the Cityvalue in the grid box next to the City element. Enter Chicago. Select the Zip valuein the grid box next to the Zip element. Enter 60611. Click the Save icon on the taskbar.
Figure 33. Enter element values
Section 8. Insert an XML document into an XML column
Use the XML Cell Editor to insert the SampleSchema.xml XML document into theDOC column in the XMLSample table. In this section, accomplish the followingtasks:
• Validate XML document SAMPLESCHEMA.XML with XMLVALIDATE
• Insert SAMPLESCHEMA.XML into XML column DOC in tableXMLSAMPLE
• View SAMPLESCHEMA.XML in table XMLSAMPLE
Insert an XML document into an XML column
In the Database Explorer view, expand the SAMPLE database schema tree.Right-click the XMLSAMPLE table node. Select Data > Edit to launch the TableData Editor.
Figure 34. Launch the Table Data Editor
The last row of the table data editor has a new row in the XML column. Click on theellipses button to launch the XML Cell Editor. Select Import to import the XMLdocument from a file system.
Figure 35. XML Cell Editor new row
Select SampleSchema.xml in the XMLBasic folder. Select Open.
The XML document is added as a row in the Table Data Editor.
Figure 39. New row in Table Data Editor
Click the Save icon on the task bar. The row is validated against the registeredschema called SampleSchema and inserted into the XMLSAMPLE table. On theData Output view, verify the INSERT and XMLVALIDATE statements ransuccessfully. You should see Status = Success, Action = Edit, and Object Name =XMLSAMPLE. In the Messages tab, you should see the message Inserted 1row(s).
In the Database Explorer view, expand the SAMPLE database schema tree.Right-click the XMLSAMPLE table node. Select Data > SAMPLE Contents toretrieve sample data.
Figure 41. New row Data Output view
On the Data Output view, verify sample data was returned. You should see Status =Success, Action = Run, and Object Name = Sample Contents. In the Results tab,you should see one row returned. Click on the ellipses button to launch the sourcewindow. Select XML Tree to see a graphical view of the SampleSchema XMLdocument stored in the XMLSAMPLE table.
Use XQuery Builder to create an XQuery. The XQuery Builder interprets user GUIactions into queries without exposing you to language semantics. The XQueryBuilder tool creates a tree view of an instance of the XML document, which will bequeried. You can drag and drop nodes from the node tree view to the design grid(s).
The design grid(s) are context sensitive and represent different XQuery languagefunctions. Build the XQuery by adding resources to these grids and drilling into theseresources. Different resources represent different functionality in the XQuerylanguage and thus present different grid sets. The query is internally represented asan XML model. Each resource added into the grid is added to the XML model.
You must associate a representative sample document used to build the XQuerywith an XML column in the table. The instance of the XML document can be locatedin the file system or in the database from an XML column in a table. Dragging and
dropping nodes from the sample XML document tree to a row on the design gridresults in the creation of an XPath object in the XQuery model. This XPath objectrepresents the node path in the target XML document.
XQuery is passed to DB2 using the XQuery language keyword XQUERY or theSQL/XML language function XMLQUERY. Only the SQL/XML language functionXMLQUERY allows runtime parameters to be passed into the XQuery. Since mostqueries contain predicates that are populated at runtime, the XQuery Builder onlygenerates SQL/XML language queries. Also, SQL/XML queries are easy to embedin SQL statements created with the SQL Query Builder.
In this section, accomplish the following tasks:
• Select representative XML document SAMPLESCHEMA.XML
• Associate representative XML document SAMPLESCHEMA.XML withXML column DOC in table XMLSAMPLE
• Build XMLQuery statement in the XQuery Builder
• Run the XMLQuery statement
• View the query output
Create an XQuery
In the Data Project Explorer view, expand the XMLBasic project tree. Right-click theXML Queries node. Select New XML Query to launch the XQuery Builder.
Figure 43. Launch the XQuery Builder
Type the name SampleQuery in the File name text box, then click Next.
To build an XQuery, use sample XML documents to represent the XML hierarchicalstructure. The representative XML document can be loaded from the file system orfetched from the database. You will load the document from the file system. ClickAdd. Select the Local workspace option. Select Browse, then choose theSampleSchema.xml. Click OK. Click Finish.
Figure 45. Select the representative document
SampleSchema.xml is the representative document. Click Next.
Representative documents must be associated with XML columns so that the queryis built to obtain data from those columns. Select SampleSchema.xml. ClickAssociate.
Figure 47. Launch associate
Expand XMLSAMPLE table node. Select DOC. Click OK.
Drag and drop the customerinfo node from the SampleSchemal.xml tree view to arow on the design grid. The node name appears in the grid and a drill down buttonappears at the end of the row.
Figure 50. Drag a resource onto the grid
Click Step into at the end of the customerinfo row in the design grid. If the Step intobutton is not visible, select the customerinfo row. The FLWOR grid appears. Thevariable customerinfo, which contains the original XPath object that represented thecustomerinfo node in the sample XML document, is created and populated in theFLWOR grid.
Figure 51. Drill into a resource
Add a WHERE predicate to the FOR logic. Drag and drop the Name element from theSampleSchema.xml tree view to the Operand1 column in the where grid. Click theOperator column in the where grid to display a list of all comparison operatorspossible in the WHERE clause. Select the = operator. Enter Smith in the Operand2column in the where grid. Click the Save icon on the task bar.
Click the Source tab, and view the generated query. Expand the outline view of theXQuery to view the query in a graphical format.
Figure 53. View query in Source and Outline views
Select XQuery > Run on the menu bar to execute the query. Click Finish.
Figure 54. XQuery context menu
On the Data Output view, verify the query ran successfully. You should see Status =Success, Action = Run, and Object Name = SampleQuery.xqm. In the Results tab,you should see one document returned. Click on the ellipses button to launch thesource window. Select XML Tree to see a graphical view of the SampleSchemaXML document stored in the XMLSAMPLE table.
Section 10. Create a stored procedure for XML data
Introduction
Use the Stored Procedure Wizard to create a stored procedure that contains anXQuery. Stored procedures created in either SQL or Java can return result sets thatcontain XML columns. In this section, accomplish the following tasks:
In the Data Project Explorer view, expand the XMLBasic project tree. Right-click theStored Procedures folder. Select New > Stored Procedure to launch the StoredProcedure Wizard. Click Next to continue.
Figure 56. Launch the Stored Procedure Wizard
In the Name and Language window, type XMLSP in the Name text box. Click Next.
Figure 57. Name and language
Select Import to import the SampleQuery.xqm SQL query statement from the
In the Deploy Options window, type XMLSP1 in the Specific name text box. Selectthe Deploy check box. Click Next. Click Next on the Code fragments window. ClickFinish on the Summary window.
The stored procedure XMLSP is built and deployed to the database. XMLSPappears under the Stored Procedures folder in the Data Project Explorer view. TheCREATE PROCEDURE statement appears in the XMLSP editor. Check for asuccessful deploy of the XMLSP stored procedure in the Data Output view.
Figure 61. XMLSP editor
In the Database Project Explorer view, select the XMLSP stored procedure underthe Stored Procedures folder in the XMLBasic project. Right-click, and select theRun menu option.
On the Data Output view, verify that the stored procedure ran successfully. Youshould see Status = Success, Action = Run, and Object Name = XMLSP. In theResults tab, you should see one document returned. Click on the ellipses button tolaunch the source window. Select XML Tree to see a graphical view of theSampleSchema XML document stored in the XMLSAMPLE table.
• developerWorks resource page for DB2 for Linux, UNIX, and Windows: Findarticles and tutorials and connect to other resources to expand your DB2 skills.
• developerWorks Information Management zone: Expand your skills on IBMInformation Management products.
• Learn about DB2 Express-C, the no-charge version of DB2 Express Edition forthe community.
• DB2 training sites list several learning delivery methods for the use of DB2. .
• Stay current with DB2 events atvia developerWorks technical events andWebcasts.
Get products and technologies
• Download a free trial version ofDB2 9.1.
• Now you can use DB2 for free. Download DB2 Express-C, a no-charge versionof DB2 Express Edition for the community that offers the same core datafeatures as DB2 Express Edition and provides a solid base to build and deployapplications.
• Download the DB2 Developer Workbench.
Discuss
• Participate in the discussion forum for this content.
• Participate in developerWorks blogs and get involved in the developerWorkscommunity.
About the author
Debra R. EatonDebra Eaton has worked in DB2 Technical Sales as a Software InformationTechnology Specialist on the DB2 Migration Team for 10 years. She specializes inconverting customer applications from non-DB2 databases to DB2. She has authoredIBM Redbooks, white papers, and DB2 Magazine articles on topics related to DB2application development. In addition, she has presented these topics at IDUG andDB2 technical conferences.