Sunteți pe pagina 1din 38

DB2 Practical

DB2 Express-C 10.5 Version

Faculty of Information Science 1


Outline

• What is XML Database?


• Relational Database and XML Databases
• Install DB2
• DB2 Quick Start
• Xpath
• XQuery

Faculty of Information Science 2


What is XML Database?
•XML-enabled Database
- Database that provides with data-
centric store and retrieve facilities to map XML
to conventional databases such as Relational
Database. It accepts XML as input and renders
XML as output
• Native XML Database
- Database that provides with document
centric store and retrieve facilities to use XML
documents as the fundamental unit of
storage but not text formatted files. Specific
query languages are also provided such as
XQuery, XPath, XQuery Update Facility, and
some others
Faculty of Information Science 3
Relational Database and XML
Databases
Relational Database XML Database
Fully Normalized Well Normalized
Solid Data Type (Schema is Flexible Data Type (Schema is
Data Structure
required) option)
Set Order
Query Language SQL XQuery
Process complex data structure
which is difficult to normalize
Compact Storage Size
Flexibility of data structure
Advantages High Performance Data
changes
Processing
during software development
phase
Difficulty of processing
complex data structure Storage Size
Disadvantages Difficulty of data structure Performance of Data
changes during software Processing
development phase
Table 1 – Relational Database and XML Database

Faculty of Information Science 4


DB2 Installation
• Download from
http://www-01.ibm.com/software/data/db2/linux-unix-
windows/downloads.html
• Install “v10.5_win_expc”. The installer is version 10.5 for
window.
• “Start Menu”-> DB2 Command Line Processor
• Extract “bookshop.zip”

Faculty of Information Science 5


DB2 Quick Start
• db2start and db2stop,
Starts and stops DB2 Instance
• -- Start DB2 instance from db2
db2 => db2start
-- Stop DB2 instance from db2
db2 => db2stop
-- Quit from db2 Command Window
db2 => quit
• Create Database
• Creates BOOKSHOP database as follows:
• -- Create BOOKSHOP database
db2 => CREATE DATABASE BOOKSHOP ON C:\
• LIST DB DIRECTORY
- Returns list of databases
• -- List Databases Faculty of Information Science 6
db2=>LIST DB DIRECTORY
DB2 Quick Start
• CONNECT TO database_name
Connects database specified by database_name
• -- Connect to the database
db2=> CONNECT TO BOOKSHOP
• LIST TABLES
Returns list of tables in the connected database
• -- List Tables
db2=> LIST TABLES
• CONNECT RESET
Disconnects from the connected database
• -- Disconnect from the database
db2=> CONNECT RESET

Faculty of Information Science 7


DB2 Quick Start
• Create a Table
Use The Command Window to create BOOK table as follows:
-- Create BOOK table
db2 => CREATE TABLE BOOK( BOOK_ID INT NOT NULL ,
BOOK_INFO XML )
• DESCRIBE TABLE table_name
Describes the table definitions
-- Describe BOOK table definitions
db2=> DESCRIBE TABLE BOOK
• Read Data Files (bookshop.zip folder)
Copy book.csv file to your installation directory (C:\Program
Files\IBM\SQLLIB\BIN) and sample XML files under ./xmlfiles sub
directory (C:\Program Files\IBM\SQLLIB\BIN\xmlfiles)

Faculty of Information Science 8


DB2 Quick Start
• Load Sample Data
-Use The Command Window to load sample book data as
follows:
-- Load Book Table
db2=> LOAD FROM book.csv OF DEL XML FROM
./xmlfiles INSERT INTO BOOK
-- Check data loading into the Book table
db2 => select book_id from book

Faculty of Information Science 9


Inserting XML Data Manually
CREATE TABLE Customer (Cid BIGINT NOT NULL PRIMARY KEY, Info XML)

INSERT INTO Customer (Cid, Info) • INSERT INTO Customer (Cid,


VALUES Info) VALUES (1002,
(1000, ‘<customerinfo '<customerinfo
xmlns="http://posample.org" xmlns="http://posample.org"
Cid="1000"> Cid="1002"> <name>Jim
<name>Kathy Smith</name> Noodle</name> <addr
<addr country="Canada"> country="Canada"> <street>25
EastCreek</street>
<street>5 Rosewood</street> <city>Markham</city>
<city>Toronto</city> <provstate>Ontario</prov-state>
<provstate>Ontario</prov-state> <pcode-zip>N9C 3T6</pcode-zip>
<pcode-zip>M6W 1E6</pcode-zip> </addr> <phone type="work">905-
</addr> 555-7258</phone>
<phone type="work">416-555- </customerinfo>')
1358</phone>
Faculty of Information Science 10
</customerinfo>’)
What is XPath?
• To understand what the XPath is at first of all, Table below
illustrates a
• simple comparison of data selecting approach in between
Relational
• Database (SQL) and XML database (XQuery and XPath).

Faculty of Information Science 11


XPath Basics

Faculty of Information Science 12


XPath Basics
• First example of the XPath is /book/title. This XPath returns the
title element node and its text node is something like cutting
from the title node of the element in the sample XML document
by using scissors as can be seen the image in Figure below:

Faculty of Information Science 13


XPath Basics
• Example XPath for Figure above:
• -- XPath
/book/title
-- XPath result
<title>Mingalabar XML</title>
• text()
If XPath result to be returned as only text node of the element, function text()
can be used as example below:
• -- XPath
/book/title/text()
-- XPath result
Mingalabar XML
• At mark (@)
XPath can select attribute of the element as well by using @ as another
example below:
• -- XPath
• /book/fn:data(@isbn-10)
-- XPath result
<book isbn-10=”1111111111”><title>Mingalabar
Faculty of Information Science XML</title> ... 14
XPath Basics
• Asterisk (*)
Asterisk (*) is used to select all for both element and attribute as example below:
• -- XPath to select all authors element
• /book/authors/*
• -- XPath to select all attributes under the book element
• /book/fn:data(@*)
Note: fn:data is a function to serialize attribute value

• Sequence index
Element_name[index] can select element node of selected index number. The index
number starts from 1.
• -- XPath to select all titles element
/book/authors/author[1]
/book/authors/author[2]
/book/authors/author[3]

• Conditional selection with predicate


Predicate will be written within [] in XPath with operator like = as example below:
• -- XPath to select books with category of “XML”
/book[categories/category='XML']

Faculty of Information Science 15


Exercise
• Start Command Editor
• Connect to BOOKSHOP
• Select all books in the XML documents
-- Select all books title
xquery db2-fn:xmlcolumn('BOOK.BOOK_INFO')/book/title
Note:
xquery: The command to let DB2 understand this is XQuery not
SQL
fn:xmlcolumn: DB2 specific function to obtain node from
selected position of the XML document
• Select not existed location in the XML documents
-- Select not existed location
xquery db2-fn:xmlcolumn('BOOK.BOOK_INFO')/book/bookname
• Note:
Null sequence will be returned instead of not found error

Faculty of Information Science 16


XPath Quiz

• Select price of the books


• Select title of the books with price in between
more than 30 to less than 40
• Select books under the category of “Database”

Faculty of Information Science 17


Answer
• Select price of the books
xquery db2-fn:xmlcolumn('BOOK.BOOK_INFO')
/book/fn:data(@price)
• Select title of the books with price in between more than
30 to less than 40
xquery db2-fn:xmlcolumn('BOOK.BOOK_INFO')
/book/title[../fn:data(@price) >= '30' and ../fn:data(@price)
< '40']
• Select books under the category of “Database”
xquery for $x in db2-
fn:xmlcolumn('BOOK.BOOK_INFO') where
$x/book/categories/category/fn:data(@category_id)="7"
return
$x/book/title

Faculty of Information Science 18


xquery db2-fn:xmlcolumn('BOOK.BOOK_INFO')/book/fn:data(@price)
xquery db2-fn:xmlcolumn('BOOK.BOOK_INFO')/book/title[../fn:data(@price)>=30 and
../fn:data(@price)<40]
xquery for $x in db2-fn:xmlcolumn('BOOK.BOOK_INFO') where
$x/book/categories/category/fn:data(@category_id)="7" return $x/book/title
xquery db2-
fn:xmlcolumn('BOOK.BOOK_INFO')/book/title[../categories/category/fn:data(@category_id)
=7]
xquery db2-
fn:xmlcolumn('BOOK.BOOK_INFO')/book/authors[../categories/category/fn:data(@category
_id)=7]
xquery db2-
fn:xmlcolumn('BOOK.BOOK_INFO')/book/categories[../categories/category/fn:data(@categ
ory_id)=7]
xquery for $x in db2-fn:xmlcolumn('BOOK.BOOK_INFO') let $y :=
fn:replace($x/book/published_date, '/', '-')
where fn:year-from-date(xs:date($y)) = 2008 return $x/book
xquery for $x in db2-fn:xmlcolumn('BOOK.BOOK_INFO') let $y :=
fn:replace($x/book/published_date, '/', '-')
where fn:month-from-date(xs:date($y)) = 7 return $x/book/title
Faculty of Information Science 19
Query Statement
• UPDATE BOOK SET BOOK_INFO = XMLQUERY('copy $n:=$BOOK_INFO
modify do delete
$n/book/language return $n') WHERE BOOK_ID = 1
• UPDATE BOOK SET BOOK_INFO = XMLQUERY( 'copy $n:=$BOOK_INFO
modify do insert
<language>English</language> after $n/book/title return $n') WHERE
BOOK_ID = 1
• UPDATE BOOK SET BOOK_INFO = XMLQUERY('copy $n:=$BOOK_INFO
modify do replace value of
$n/book/language with “Myanmar” return $n') WHERE BOOK_ID = 1
• xquery for $x in db2-fn:xmlcolumn('BOOK.BOOK_INFO')/book/language/text()
order by $x descending return $x
• xquery for $x in db2-fn:xmlcolumn('BOOK.BOOK_INFO')/book/language/text()
return $x
• xquery db2-fn:xmlcolumn('BOOK.BOOK_INFO')/book/language[../id=1]
• UPDATE BOOK SET BOOK_INFO = XMLQUERY('copy $n:=$BOOK_INFO
modify do replace value of
$n/book/@isbn-10 with “1234567890” return $n') WHERE BOOK_ID = 1

Faculty of Information Science 20


• • XQuery uses functions to extract data from XML
documents.
• The doc() function is used to open the "books.xml" file:
doc("books.xml")
• XQuery uses path expressions to navigate through elements
in an XML document.
• The following path expression is used to select all the title
elements in the "books.xml" file:
• doc("books.xml")/bookstore/book/title
• XQuery uses predicates to limit the extracted data from
XML
documents.
• doc("books.xml")/bookstore/book[price<30]

Faculty of Information Science 21


XPath Path Expressions
• XPath uses path expressions to select nodes or node-sets
in an XML document.
• These path expressions look very much like the
expressions you use with a traditional computer file
system:
• XPath includes over 100 built-in functions.
• There are functions for string values, numeric values,
booleans, date and time comparison, node manipulation,
sequence manipulation, and much more.
• Today XPath expressions can also be used in JavaScript,
Java, XML Schema, PHP, Python, C and C++, and lots
of other languages.

Faculty of Information Science 22


What is XQuery?
• XQuery is a query language for XML to extract and manipulate
data from XML documents, and it consists of following two
specifications (FLWOR will be discussed in next section):
– XPath
– FLWOR (For… let… where… order by… return)

Faculty of Information Science 23


XQuery Basics
• FLWOR
• FLWOR (pronounced as 'flower') is defined by XQuery as an
expression that comes with the five clauses and it supports
iteration and binding of variables to intermediate results.
• Those five clauses are FOR, LET, WHERE, ORDER BY,
RETURN, and the FLWOR can be used to provide join-like
functionality to XML documents as well. Most of those clauses
are optional except RETURN is the only clause that's always
present is the XQuery:
– F (For): Select/Creates a sequence of records
– L (Let): Binds a sequence to a variable
– W (Where): Filters the records with specified condition
– O (Order by): sorts the records either by ascending or
descending
24
– R (Return): Gets evaluated
Faculty of Information Science
once for every record
Example FLOWR Expression
• First FLWOR to return the list of books under the category of
XML
• xquery
• for $x in db2-fn:xmlcolumn('BOOK.BOOK_INFO') where
• $x/book/categories/category/fn:data(@category_id)="6"
• return
• <result>{$x/book/title/text()}</result>

• -- Result will be shown like below:


• <result>
• Introduction to XML Database
• </result>

Faculty of Information Science 25


XQuery Data Types
Data Type Description
String String
Boolean Boolean (True/False)
Decimal Decimal Number
Float 32-bit single floating point
Double 64-bit double floating point
duration Duration (Date and Time)
datetime Date and Time
Time Time
Date Date

Faculty of Information Science 26


XQuery Functions

Faculty of Information Science 27


XQuery Operators
• Table below is a list of commonly used XQuery, XPath
operators. Details of each
function and operator, and some others can be found at W3C
Technical Reports and
Publications website at: http://www.w3.org/TR/xquery-
operators/
Operator Description
AND And
OR Or
= Equal
!= Not Equal
< Smaller than
<= Smaller than or equal
> Greater than
>= Greater than
Faculty of Information or equal
Science 28
XQuery Examples
• For and let
for iterates over an input sequence and calculates values
for each item in that sequence then returns a sequence
obtained by concatenating the results. Example below
iterates 3 times to return concatenated output element such
as “Exercise 1”.
let declares a variable and gives it a value. In this example,
a string value of “Exercise” will be set in the variable of y:
xquery
for $x in (1,2,3)
let $y:= ('Exercise')
return <output>{$x, $y}</output>

Faculty of Information Science 29


Xml: Where
• Where
This is similar to SQL WHERE clause with condition to filter
the result. Example below filters under the category of
“Database” books:
xquery
for $x in db2-
fn:xmlcolumn('BOOK.BOOK_INFO') where
$x/book/categories/category/fn:data(@category_id
)=“7”
return
<result>{$x/book/title/text()}</result>

Faculty of Information Science 30


Xml: Order by

This is also similar to SQL ORDER BY to sort whether by
ascending or descending orders:
xquery
for $x in db2-
fn:xmlcolumn('BOOK.BOOK_INFO')/book/title/text()
order by $x ascending
return $x

xquery
for $x in db2-
fn:xmlcolumn('BOOK.BOOK_INFO')/book/title/text()
order by $x descending
return $x

Faculty of Information Science 31


• Date type
In XQuery, the date format is fixed as „yyyy-mm-dd‟ thus
it is necessary to convert by using fn:replace function if the
date format is not the same as above. To extract the year
from the date, fn:year-from-date function will be used
(fn:month-from-date and fn:day-from-date are same
function for month and day)
xquery
for $x in db2-fn:xmlcolumn('BOOK.BOOK_INFO')
let $y := fn:replace($x/book/published_date, '/', '-')
where fn:year-from-date(xs:date($y)) = 2008
return
$x/book

Faculty of Information Science 32


XQuery Update Facility
• XQuery Update Facility (http://www.w3.org/TR/2008/CR-
xquery-update-10-20080801/) is an extension of XQuery
which provides update/delete/insert facilities for XML
Documents, Elements, and Attributes that can be used to
make persistent changes to instances of the XML data model.
• Following list is basic commands provided by the Candidate
XQuery Update
Facility as :
– transform: Update XML document
– insert: Insert elements
– delete: Delete elements
– replace: Update element values
– rename: Rename element name

Faculty of Information Science 33


XQuery Update Facility
• Replace value of: Update text value of the selected element
Example below is to update text node of the language element from
“English” to “Myanmar” for BOOK_ID is 1 in the BOOK table by
using “replace value of”.

UPDATE BOOK
SET BOOK_INFO = XMLQUERY(
'copy $n:=$BOOK_INFO
modify do replace value of $n/book/language
with "Myanmar" return $n')
WHERE BOOK_ID = 1

• To retrieve :
xquery for $x in db2-
fn:xmlcolumn('BOOK.BOOK_INFO')/book/language/text() order by $x
descending return $x

Faculty of Information Science 34


Delete: Delete selected element
– Example below is to delete the language element of the
BOOK_ID is 1 in BOOK table by using “delete”:
UPDATE BOOK
SET BOOK_INFO = XMLQUERY(
'copy $n:=$BOOK_INFO
modify do delete $n/book/language
return $n')
WHERE BOOK_ID = 1

Faculty of Information Science 35


Insert: Add an element
• Example below is to add new language element of the BOOK_ID
is 1 in BOOK table by using “insert”:

UPDATE BOOK
SET BOOK_INFO = XMLQUERY(
'copy $n:=$BOOK_INFO
modify do insert <language>English</language>
after $n/book/title return $n')
WHERE BOOK_ID = 1

Faculty of Information Science 36


Replace values of: Update attribute
value
• Example below is to update ISBN-10 attribute under the book element
with the BOOK_ID is 1 in BOOK table by using “replace value of”:
UPDATE BOOK
SET BOOK_INFO = XMLQUERY(
'copy $n:=$BOOK_INFO
modify do replace value of $n/book/@isbn-10
with “1234567890”
return $n')
WHERE BOOK_ID = 1

• To retrieve:
xquery for $x in db2-fn:xmlcolumn('BOOK.BOOK_INFO')
where $x/book/fn:data(@isbn-10)="1234567890"
return
<result>{$x/book/title/text()}</result>

Faculty of Information Science 37


XQuery Quiz
• Returns Multiplication table (up to 9 times 9) like sample below
<fact>
1 times 1 = 1
</fact>
...
<fact>
9 times 8 = 72
</fact>
<fact>
9 times 9 = 81
</fact>
• Returns list of price by ascending order in following format
<price>
18
</price>
<price>
20
</price>
...

Faculty of Information Science 38

S-ar putea să vă placă și