Download presentation
Presentation is loading. Please wait.
1
WEB DATABASE BY SEONGGYU KIM
2
Web Database Web (SQL) Database is a web page API for storing data in databases that can be queried using a variant of SQL W3C Web Applications Working Group ceased working on the specification due to the lack of independent implementations XML database a data persistence software system that allows data to be stored in XML format, and these data can then be queried
3
Objectives of Database Systems
Data Sharing Controlled Amount of Data Redundancy Data Independence Represent Objects & Relationships Maintain Data Integrity - Consistency Efficient Physical Database Design Security
4
Data Abstraction Logical Data Independence Physical Data Independence
5
Database System
6
Data Models Hierarchical Data Model Network Data Model
a collection of conceptual tools for describing data, relationships among data, integrity constraints Hierarchical Data Model Network Data Model Relational Data Model Object-oriented Data Model Deductive & Object-oriented Data Model
7
E-R Diagram
8
Relational Database
9
Network Database
10
Hierarchical Database
11
Deductive and Object-oriented Database
lowery[name → “Lowery”, street → Maple:Evanston, deposit → acc1[number → 900, amount → 55]] shiver[name → “Shiver”, street → North:Bronx, deposit → {acc2, acc3}] hodges[name → “Hodges”, street → Sidehill:Brooklyn, deposit → {acc3, acc4}] acc2:account[number → 556, amount → ] acc3[number → 647, amount → ] acc4[number → 801, amount → 10533]
12
Differences among the Models
relationship - pointer, values predefined relationship object identifier type hierarchy deduction
13
A Classification of Database Programming Languages
14
Database Design Proper structure of tables
Proper relationships among tables Appropriate data constraints Database design from existing data analyze data tables, extract data from them, and apply normalization Database design from New system development create a data model from users’ requirements and transform it Database design from redesign migrate database or integrate two or more databases to newer databases
15
Phases of Database System Design
16
Entity Relationship Model
Entity - an existing object, distinguishable from other objects represented by a set of attributes Relationship - an association among entities
17
ER Diagram 1
18
ER Diagram 2 Weak Entity
19
The Jefferson Dance Club
Charges $45 / hour per Student (Couple) for a Private Lesson $6 / hour per Student of a Group Lesson Offers Private Lesson from noon to 10 pm, six days / week Group Lesson in the evenings Employs Full-time instructor paid a fixed amount / week Part-time instructor paid a fixed amount / hour Requirements - keep track of students and the classes types and times of classes each instructor has
20
ER Diagram 3
21
ER Diagram 4
22
Relationships among Relationships
Redundant
23
Aggregation
24
Normalization Good Database Design using Functional Dependencies
Side Effects
25
2nd Normal Form Key ® Nonkey attributes (SID, Activity) → Fee
SA(SID, Activity) SID Activity 100 Skiing 150 Squash Swimming 175 200 ACF(SID, Activity, Fee) SID Activity Fee 100 Skiing 200 150 Squash 50 Swimming 175 AF(Activity, Fee) Activity Fee Skiing 200 Swimming 50 Squash (SID, Activity) → Fee Activity → Fee
26
3rd Normal Form No Transitive Dependency SB(SID, Building)
SBF(SID, Building, Fee) SID Building 100 Randolph 150 Ingersoll 200 250 Pitkin 300 SID Building Fee 100 Randolph 1200 150 Ingersoll 1100 200 250 Pitkin 300 ST(Building, Fee) Building ® Fee SID ® Building ® Fee Building Fee Randolph 1200 Ingersoll 1100 Pitkin
27
Boyce-Codd Normal Form
Every Determinant is a Candidate Key SID Fname 100 Cauchy 150 Perls 200 Kim 250 300 Norman SID Major Fname 100 Math Cauchy 150 Psychology Perls 200 CS Kim 250 Economics 300 Norman Fname Major Cauchy Math Perls Psychology Kim CS Economics Norman (SID, Major) ® Fname (SID, Fname) ® Major
28
4th Normal Form BCNF & No Multivalued Dependencies SID →→ Major
Activity 100 Music Swimming CS Tennis 150 Math Jogging 200 SID MAJOR 100 Music CS 150 Math 200 SID ACTIVITY 100 Swimming Tennis 150 Jogging 200 SID →→ Major SID →→ Activity 100 Music Skiing CS
29
Lossy Join PCZ = ({Phone, Company, Zip},
Phone Company, Zip Company) COMPANY ZIP Edison 60025 61136 PHONE COMPANY ZIP Edison 60025 61136 PHONE COMPANY Edison
30
Lossless Join R R1 and R2 R1 R2 is lossless if R1 R2 R1 or R1 R2 R2 R(Project, Manager, Employee#) R1(Project, Manager) R2(Employee#, Manager) Lossy R3(Manager, Project) R4(Employee#, Manager) Lossless
31
5th Normal Form Lossless Join SIN(SID, Name) SIBLDG(SID, Building)
Fee 100 Jones Randolph 1200 150 Hayes Ingersoll 1100 175 Jackson 1500 200 Pitkin 1050 215 Turner SIN(SID, Name) SIBLDG(SID, Building) SIF(SID, Fee)
32
Domain/Key Normal Form
All Constraints on relations are logical Consequences of domains and keys STUDENT(SID, GradeLevel, Building, Fee) Constraints Building ® Fee SID must not begin with digit 1 Domain Definitions SID IN CDDD, where C ¹ 1 digit, D digit GradeLevel IN {‘FR’, ‘SO’, ‘JR’, ‘SN’, ‘GR’} Building IN CHAR(4) Fee IN DEC(4) Relation and Key Definitions STUDENT(SID, GradeLevel, Building) BLDG-FEE(Building, Fee)
33
Transformation of ER Models into Relational Database Designs
Binary Relationships Entity Þ Normalized Relation Weak Entity Þ ID Dependent Relation
34
Ternary Relationship
35
Binary Relationship
36
Representing Binary Relationships
1:1 or 1:N Relationships EMPLOYEE(EmpNO, EmpName, Phone, Address) AUTO(LicenseNo, SerialNo, .., Year, EmpNo) EMP-JOB-EVAL(EmpNO, EmpName, ..., Grade)
37
Representing Binary Relationships
M:N Relationships STUDENT(StudentNO, StudentName) CLASS(ClassNO, ClassName) IN(ClassNo, StudentNo)
38
Representing Binary Relationships
Weak Entity INVOICE(InvNO, CustNo, Date, ..) LINE-ITEM(InvNO, LineNo, ItemNO, Qty, ..)
39
Representing Binary Relationships
Recursive Relationships Customer Number Referred Customers , 400 , 700 CUSTOMER(CustNo, CustName, Phone, ReferredBy)
40
Representing Binary Relationships
ISA Relationships INST(InsNO, Name, Addr,..) FT-INST(InsNO, APPW) PT-INST(InsNO, APPH)
41
Relational Data Manipulation
Procedural - how to do Relational Algebra Declarative - what to do Relational Calculus Structured Query Language Query By Example
42
DML Interfaces to DBMS Means of Forms Query Language
Application Program Interface - subroutine calls, data access commands in programs in Java, C, Pascal, etc. - languages provided by DBMS impedance mismatch
43
Relational Algebra Unary Operator Selection Projection Rename
Binary Operator - logical domains should be the same Product Join Union Intersection Difference Division
44
SQL - 92 Data Definition Language Data Manipulation Language
View Definition Authorization Integrity Transaction Control
45
Schema Definition in SQL
CREATE TABLE RelationName ([AttributeName DataDefinition]+ [integrity constraints]*) CREATE TABLE account (account_number char(10) not null, branch_name char(15), balance integer, primary key (account_number), check (balance >= 0))
46
SQL - Query SELECT [distinct] attributes [Aggregate functions*]
FROM relations [WHERE conditions [in (SQL)] [EXISTS / NOT EXISTS (SQL)]] [ORDER / GROUP BY attributes] [HAVING Aggregate functions*] Aggregate functions - avg, min, max, sum, count
47
Example Tables Student Enrollment Class SID Name Major Grade Level Age
100 JONES History GR 21 150 PARKS Accounting SO 19 200 BAKER Math 50 250 GLASS SN 300 41 350 RUSSEL JR 20 400 RYE FR 18 450 24 Enrollment Student Number Class Name Position No 100 BD445 1 150 BA200 200 2 CS250 300 CS150 400 BF410 450 3 Class Name Time Room BA200 M-F9 SC110 BD445 MWF3 SC213 BF410 MWF8 CS150 EA304 CS250 MWF12 EB210
48
SQL - Example 1 SELECT Major FROM STUDENT
SELECT SID, Name, Major, GradeLevel, Age FROM STUDENT WHERE Major = ‘Math’ WHERE Major IN (‘Math’, ‘Accounting’)
49
SQL - Example 2 SELECT Name, Major, Age FROM STUDENT
WHERE GradeLevel IN (‘GR’, ‘SO’, ‘SN’) ORDER BY Name ASC, Age DEC SELECT COUNT(DISTINCT Major) FROM STUDENT
50
SQL - Example 3 SELECT Major, COUNT(*) FROM STUDENT GROUP BY Major
HAVING COUNT(*) > 2 SELECT Major, AVG(Age) FROM STUDENT WHERE GradeLevel = ‘SN’ GROUP BY Major HAVING COUNT(*) > 1
51
SQL - Example 4 SELECT DISTINCT ClassName FROM ENROLLMENT
WHERE StudentNumber IN (SELECT SID FROM STUDENT WHERE GradeLevel NOT = ‘GR’) SELECT DISTINCT ENROLLMENT.ClassName FROM ENROLLMENT, STUDENT WHERE ENROLLMENT.StudentNumber = STUDENT.SID AND STUDENT.GradeLevel NOT = ‘GR’
52
SQL - Example 5 SELECT DISTINCT StudentNumber FROM ENROLLMENT A
WHERE EXISTS (SELECT * FROM ENROLLMENT B WHERE A.StudentNumber = B.StudentNumber AND A.ClassName NOT = B.ClassName)
53
SQL - insert, delete, update
INSERT INTO relation [(attributes)] VALUES [(values) | (SQL)] DELETE relation WHERE condition [IN (SQL)] UPDATE relation SET new value into attribute WHERE condition
54
SQL - Example 6 INSERT INTO ENROLLMENT VALUES (400, ‘BD445’, 44)
DELETE ENROLLMENT WHERE ENROLLMENT.StudentNumber IN (SELECT STUDENT.SID FROM STUDENT WHERE STUDENT.Major = ‘Accounting’) UPDATE CLASS SET ClassName = ‘BD564’ WHERE ClassName = ‘BD445’
55
Referential Integrity
CREATE TABLE customer (customer_name char(20) not null, customer_phone char(12), primary key (customer_name)) CREATE TABLE account (account_no char(10) not null, balance integer, primary key (account_no) check (balance >= 0)) CREATE TABLE depositor (customer_name char(20) not null, account_no char(10) not null, primary key (customer_name, account_no), foreign key (customer_name) references customer, foreign key (account_no) references account) on delete / update relation
56
Web Interface to Database
Network Database Applications Database applications on Internet and Intranet Static Report Publishing DB Query Publishing Private Network Public Network via Firewall Web (SQL) Database
57
Database Access Standards
Three-tier architecture Standard & DBMS-independent Interfaces for accessing database server Browser DB Web Server Database Server Browser ODBC ADO (Active Data Object) OLE/DB JDBC Native Calls HTML DHTML XML
58
Role of ADO Browser Web Server ODBC DB Server RDB OLE DB ADO NRDB File
Native Interface ODBC DB Server NRDB File Multimedia Data RDB OLE DB ADO Enables programmer in almost any languages to be able to access OLD DB Works in conjunction with Remote Data Services objects
59
JDBC(Java Database Connectivity)
API for JAVA interface to Database Basic Order Connection Type 1 : JDBC-ODBC bridge driver Type 2 : Native-API partly-java driver Type 3 : JDBC-Net pure java driver Type 4 : Native-protocol pure java driver Transaction processing Disconnection
60
Database Connection //======= declaration begin===========//
static Connection conn = null; static String driver = "oracle.jdbc.driver.OracleDriver"; static String url = static String username = "csdb40"; static String passwd = "csdb40"; //========== declaration end ============// // db connection try { Class.forName(driver); conn = DriverManager.getConnection(url, username, passwd); } catch (ClassNotFoundException e) { System.out.println(e.getMessage()); } catch (SQLException se) { System.out.println(se.getMessage()); } Driver registration For JDBC-ODBC Bridge Connection con = DriverManager.getConnection("jdbc:odbc:DSName","user","pw")
61
Transaction Processing
Statement Query Types of Statement Statement (default) Statement st=con.createStatement(); ResultSet rs=st.executeQuery("select * from customer"); PreparedStatement – Parameter (“?”) PreparedStatement ps=con.prepareStatement( "update customer set c_addr=? where c_name=?); ps.setString(1,“경기도 안양시"); ps.setString(2, “홍길동"); ps.executeUpdate(); CallableStatement – calls Function, Procedure, Package
62
Query Execution Query execution ResultSet class next() Return value
executeUpdate Insert, Delete, Update, Drop, Create, Alter executeQuery Select execute when Type is ambiguous If return is true ResultSet, otherwise update st.getUpdateCound() st.getResultSet() ResultSet class Receives the result from the executeQuery of SQL Statement next() If ResultSet is not empty, move to the next row Return value True if next row is available, False otherwise ResultSet rs; Statement st; rs = st.executeQuery (“select * from customer”); while(rs.next()){ … }
63
JDBC 2.0 methods ResultSet insert, update, delete in ResultSet
rs.next(), rs.previous(), rs.first(), rs.last() insert, update, delete in ResultSet rs.insertRow(), rs.updateRow, rs.deleteRow() Close() method shall deallocate the objects generated by the driver close() classes ResultSet, Statement, Connection format rs.close(); st.close(); con.close();
64
JDBC Example createTable.java import java.sql.*;
public class createTable { public static void main(String[] argv) Connection conn; Statement stmt; try{ Class.forName("oracle.jdbc.driver.OracleDriver"); conn = DriverManager.getConnection "csdb40", "csdb40"); stmt = conn.createStatement(); stmt.executeUpdate( "CREATE TABLE createTest(" + "name VARCHAR2(10), " + "tel VARCHAR2(15))" ); System.out.println("Table Created!!!"); stmt.close(); conn.close(); }catch(Exception e) {e.printStackTrace();} }
65
Markup Languages SGML HTML D(Dynamic)HTML
Specify the appearance and behavior of Web pages SGML HTML No way to specify contents from layout & format Lack of style definitions No way to access web page elements with scripts No construct to facilitate caching & data manipulation on clients D(Dynamic)HTML Microsoft implementation of HTML 4.0 Document Object Model(DOM) enables contents to be altered without refreshing them from server Cascading Style Sheet Remote Data Service(RD), ActiveX objects for exchanging data with server
66
XML (eXtensible Markup Language)
Clear separation of contents, layout and materialization Standards, but extensible by developer Standard means for expressing the structure of database views using DTD or XML Schema No built-in compression scheme A Standardized facility to describe, validate and materialize any database view
67
XML Satellite Technologies
Core syntax XML Applications - XHTML, MathML Document Modeling - DTD, XML Schema Style & Transformation – CSS, XLS, XSLT, XSL-FO Data Addressing & Querying - XPath, XPointer, XQL Programming and infrastructure - DOM(Document Object Model) - SAX(Simple API for XML)
68
A Goofy XML Example <?xml version="1.0" ?>
<time-o-gram pri="important"> <to>Sarah</to> <subject>Reminder</subject> <message> Don't forget to recharge K-9 <emphasis>twice a day</emphasis> . Also, I think we should have his bearings checked out. See you soon (or late). I have a date with some <villain>Daleks</villain>… </message> <from>The Doctor</from> </time-o-gram> TIME-O-GRAM Priority : Important To: Sarah Subject : Reminder Don’t forget to recharge K-9 twice a day. …. From : The Doctor
69
HTML <HTML> <BODY> <TABLE> <TR> <TD> </TD> <!-ISBN-> <TD>DB</TD> <!-CATEGORY-> <TD> </TD> <!-RELEASE_DATE-> <TD>Database Processing</TD> <!-TITLE-> <TD>David M. Kroenke</TD> <!-AUTHOR-> </TR> <TD> </TD> <!-ISBN-> <TD>SCIENCE</TD> <!-CATEGORY-> <TD> </TD> <!-RELEASE_DATE-> <TD>Blink</TD> <!-TITLE-> <TD>Malcolm Gladwell </TD> <!-AUTHOR-> </TABLE> </BODY> </HTML>
70
XML Example - book.xml <?xml version="1.0" encoding="euc-kr"?> <?xml-stylesheet type="text/xsl" href="book.xsl"?> <BOOK> <ITEM> <ISBN> </ISBN> <CATEGORY>DB</CATEGORY> <RELEASE_DATE> </RELEASE_DATE> <TITLE>Database Processing</TITLE> <AUTHOR>David M. Kroenke</AUTHOR> </ITEM> <ISBN> </ISBN> <CATEGORY>SCIENCE</CATEGORY> <RELEASE_DATE> </RELEASE_DATE> <TITLE>Blink</TITLE> <AUTHOR>Malcolm Gladwell</AUTHOR> </BOOK>
71
XSL Example – book.xsl <?xml version="1.0" encoding="euc-kr"?> <xsl:stylesheet xmlns:xsl=" xmlns:fo=" rersult-ns="fo" indent-result="yes"> <xsl:template match="/"> <HTML> <HEAD> <TITLE> 교 재 </TITLE> </HEAD> <BODY> <UL> <xsl:apply-templates select="//ITEM" /> </UL> </BODY> </HTML> </xsl:template> <xsl:template match="ITEM"> <LI> <xsl:value-of /> </LI> </xsl:stylesheet>
72
XML in detail A set of rules for building markup languages
A markup language is a set of symbols that can be placed in the text of a document to demarcate and label the parts of that document Markup can be processed by computer programs
73
XML Document with a prolog and a root element
<?xml version="1.0" encoding="euc-kr“?> <!DOCTYPE book PUBLIC “-//ORA/DTD DBLITE XML//EN” SYSTEM “/usr/local/prod/dtds/dblite.dtd” [ <!ENTITY pref SYSTEM “preface.xml”> <!ENTITY agent “Gildong Hong ”> <!ENTITY xml “<acronym>XML</acronym>” ]> <book> <ITEM text=“yes”> <LONGDOC>&pref</LONGDOC> <ISBN> </ISBN> <TITLE>Database Processing</TITLE> <AUTHOR>David M. Kroenke</AUTHOR> </ITEM> … </book> Provide a way of location transparency Augment or redefine the declarations found in the external subset This ordering can not be changed Attributes modify an element’s behavior rather than hold data
74
XML Declaration <?xml version="1.0" encoding="euc-kr"?> Version
Encoding – euc-kr, utf-8 Standalone - no if there are external entities, i.e., files to load, yes otherwise <?xml version="1.0"?> <?xml version='1.0' encoding='US-ASCII' standalone='yes'?> <?xml version = '1.0' encoding= 'iso ' standalone ="no"?>
75
Document Type Declaration
specify the name of the root element the DTD to use for validating the document various parameters such as entity declarations to be used to augment or redefine the external declaration <!DOCTYPE book PUBLIC “-//ORA/DTD DBLITE XML//EN” SYSTEM “/usr/local/prod/dtds/dblite.dtd” [ <!ENTITY pref SYSTEM “preface.xml”> <!ENTITY agent “Gildong Hong ”> <!ENTITY xml “<acronym>XML</acronym>” ]>
76
Entities Placeholders for content, variables
<?xml version="1.0"?> <!DOCTYPE message SYSTEM "/xmlstuff/dtds/message.dtd" [ <!ENTITY part SYSTEM "p.xml"> <!ENTITY client "Mr. Rufus Xavier Sasperilla"> <!ENTITY agent "Ms. Sally Tashuns"> <!ENTITY phone "<number> </number>"> ]> <message> <opening>Dear &client;</opening> <body>We have an exciting opportunity for you! A set of ocean-front cliff dwellings in Piñata, They're going fast! To reserve a place for your holiday, call &agent; at ☎. Hurry, &client;. Time is running out! &part</body> </message> ñ means the character ñ <!ENTITY catalog SYSTEM " <!ENTITY faraway PUBLIC "-//BOB//FILE Catalog//EN" "
77
Elements Parts of a document
Containers with a mixture of text and other elements <ITEM text=“yes”> <LONGDOC>&pref</LONGDOC> <ISBN><EMPHASIS> </EMPHASIS></ISBN> <TITLE>Database Processing</TITLE> <AUTHOR>David M. Kroenke</AUTHOR> </ITEM> An element's start and end tags must both reside in the same parent <foo>x < y</foo> => <foo>x < y</foo>
78
Attributes convey more information about an element
can be used to give the element a unique label so it can be easily located can describe a property about the element, such as the location of a file at the end of a link can be used to describe some aspect of the element's behavior or to create a subtype Attribute values can be constrained to certain types: ID & IDREF A DTD can restrict attributes is by creating an allowed set of values <kiosk music="bagpipes" color="red" id="page-81527"> <choice test='msg="hi"'/> <team persons="sue joe jane"> <team person1="sue" person2="joe" person3="jane"> <team person="sue" person="joe" person="jane"> wrong! <team> <person>sue</person> <person>joe</person> <person>jane</person> </team> A namespace is a group of element and attribute names <hardware:nut>, <food:nut> <book:info xmlns:book=“ xmnls:author=“
79
Well Formed XML Documents
XML documents must have a root element XML elements must have a closing tag XML tags are case sensitive XML elements must be properly nested XML attribute values must be quoted Valid XML Documents a "Well Formed" XML document, which also conforms to the rules of a Document Type Definition (DTD)
80
Well formed Document some minimal rules for XML parsers to protect themselves Good Bad <list> <listitem>soupcan</listitem> <listitem>alligator</listitem> <listitem>tree</listitem> </list> <listitem>soupcan <listitem>alligator <listitem>tree <graphic filename="icon.png"/> <graphic filename="icon.png"> <a>A good <b>nesting</b> example.</a> <a>This is <b>a poor</a> nesting scheme.</b> <equation>5 < 2</equation> <example-one> <_example2> <Example.Three> <bad*characters> <illegal space> <99number-start>
81
DTD (Document Type Definition)
Consists of Elements, Attributes, Entities, Notations, CDATA Declares a set of allowed elements Defines a content model <!ELEMENT emphasis (#PCDATA)> <!ELEMENT para (#PCDATA | emphasis)*> <!ELEMENT article (title, author*, (para | list)+, bibliography?> 1:n :1 Declares a set of allowed attributes for each element <!ATTLIST memo id ID #REQUIRED security (high | low) “high” keywords NMTOKENS #IMPLIED > <!ATTLIST part instock (true | false) #IMPLIED> Provides a variety of ways to manage the model easier
82
DTD Declaration define the legal building blocks of an XML document
<!DOCTYPE NEWSPAPER [ < !ELEMENT NEWSPAPER (ARTICLE+)> < !ELEMENT ARTICLE (HEADLINE,BYLINE,LEAD,BODY,NOTES)> < !ELEMENT HEADLINE (#PCDATA)> < !ELEMENT BYLINE (#PCDATA)> < !ELEMENT LEAD (#PCDATA)> < !ELEMENT BODY (#PCDATA)> < !ELEMENT NOTES (#PCDATA)> < !ATTLIST ARTICLE AUTHOR CDATA #REQUIRED> < !ATTLIST ARTICLE EDITOR CDATA #IMPLIED> < !ATTLIST ARTICLE DATE CDATA #IMPLIED> < !ATTLIST ARTICLE EDITION CDATA #IMPLIED> ]> Nesting elements
83
Declaring Content of element type
EMPTY Refers to tags that are empty. <IMG SRC="grommit.gif"/>, or <IMG SRC="grommit.gif"></IMG>. ANY Refers to anything at all, as long as XML rules are followed. ANY is useful to use when you have yet to decide the allowable contents of the element. <!ELEMENT note ANY> children elements You can place any number of element types within another element type. These are called children elements, and the elements they are placed in are called parent elements. <!ELEMENT note (to, from, heading, body)> Mixed content Refers to a combination of (#PCDATA) and children elements. PCDATA stands for parsed character data, that is, text that is not markup. Therefore, an element that has the allowable content (#PCDATA) may not contain any children.
84
Declaring Attributes Type Description CDATA
The value is character data (en1|en2|..) The value must be one from an enumerated list ID The value is a unique id IDREF The value is the id of another element IDREFS The value is a list of other ids NMTOKEN The value is a valid XML name NMTOKENS The value is a list of valid XML names ENTITY The value is an entity ENTITIES The value is a list of entities NOTATION The value is a name of a notation xml: The value is a predefined xml value Value Explanation value The default value of the attribute #REQUIRED The attribute is required #IMPLIED The attribute is not required #FIXED value The attribute value is fixed
85
XML Elements vs. Attributes
<note date="12/11/2002"> < to>Tove</to> < from>Jani</from> < heading>Reminder</heading> < body>Don't forget me this weekend!</body> < /note> <note> < date>12/11/2002</date> < to>Tove</to> < from>Jani</from> < heading>Reminder</heading> < body>Don't forget me this weekend!</body> < /note> <note> < date> <day>12</day> <month>11</month> <year>2002</year> < /date> < to>Tove</to> < from>Jani</from> < heading>Reminder</heading> < body>Don't forget me this weekend!</body> < /note> attributes cannot contain multiple values (child elements can) attributes are not easily expandable attributes cannot describe structures (child elements can) attributes are more difficult to manipulate by program code attribute values are not easy to test against a DTD
86
Internal & External DTD
Internal DTD <?xml version="1.0"?> < !DOCTYPE note [ <!ELEMENT note (to, from, heading, body)> <!ELEMENT to (#PCDATA)> <!ELEMENT from (#PCDATA)> <!ELEMENT heading (#PCDATA)> <!ELEMENT body (#PCDATA)> ]> < note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend</body> < /note> External DTD <?xml version="1.0"?> < !DOCTYPE note SYSTEM “doc/note.dtd"> < note> < to>Tove</to> < from>Jani</from> < heading>Reminder</heading> < body>Don't forget me this weekend!</body> < /note> note.dtd <!ELEMENT note (to, from, heading, body)> < !ELEMENT to (#PCDATA)> < !ELEMENT from (#PCDATA)> < !ELEMENT heading (#PCDATA)> < !ELEMENT body (#PCDATA)> <![ INCLUDE [ <!ELEMENT PRODUCT_ID (#PCDATA)> <!ELEMENT SHIP_DATE (#PCDATA)> <!ELEMENT SKU (#PCDATA)> ]]> <![ IGNORE [ <!ELEMENT PRODUCT_ID (#PCDATA)> <!ELEMENT SHIP_DATE (#PCDATA)> <!ELEMENT SKU (#PCDATA)> ]]>
87
XML DTD The purpose of a DTD is to define the structure of an XML document. It defines the structure with a list of legal elements <!DOCTYPE note [ <!ELEMENT note (to,from,heading,body)> <!ELEMENT to (#PCDATA)> <!ELEMENT from (#PCDATA)> <!ELEMENT heading (#PCDATA)> <!ELEMENT body (#PCDATA)> ]> DTD <xs:element name="note"> < xs:complexType> <xs:sequence> <xs:element name="to" type="xs:string"/> <xs:element name="from" type="xs:string"/> <xs:element name="heading" type="xs:string"/> <xs:element name="body" type="xs:string"/> </xs:sequence> < /xs:complexType> < /xs:element> XML Schema
88
XML Schema Quite a new technology XML documents themselves
DTD - a detailed way to define what the data can and cannot contain Provide a much more powerful means by which to define your XML document structure and limitations Provide an Object Oriented approach to defining the format of an XML document With core data type along with various operators and modifiers, complex type can be created
89
Create a XML Document With DTD Kim Oh Manager Personnel department
name=“sales” employee name=“marketing” employee name title staff name title staff Kim employee employee employee employee name title name title name title name title Oh Manager
90
Relationships CREATE TABLE Invoice ( invoiceID integer PRIMARY KEY,
customerID integer, orderDate datetime, shipDate datetime) CREATE TABLE LineItem ( lineItemID integer, invoiceID integer, productDescription varchar(255), quantity integer, unitPrice float, CONSTRAINT fk_LineItemInvoice FOREIGN KEY (invoiceID) REFERENCES Invoice (invoiceID)) <!ELEMENT Invoice (LineItem+)> <!ATTLIST Invoice orderDate CDATA #REQUIRED shipDate CDATA #REQUIRED> <!ELEMENT LineItem EMPTY> <!ATTLIST LineItem productDescription CDATA #REQUIRED quantity CDATA #REQUIRED unitPrice CDATA #REQUIRED> Use of pointers – IDREF(S)-ID attributes – have a profound impact on processing performance
91
XLS(EXtensible Stylesheet Language)
CSS = Style Sheets for HTML XSL = Style Sheets for XML XSL consists of three parts: XSLT - a language for transforming XML documents XPath - a language for navigating in XML documents XSL-FO - a language for formatting XML documents XSLT = XSL Transformations Normally transforms each XML element into an (X)HTML element add/remove elements and attributes to or from the output file rearrange and sort elements, perform tests and make decisions about which elements to hide and display <xsl:stylesheet version="1.0" xmlns:xsl="
92
XSL Elements <xsl:template> element is used to build templates
match attribute is used to associate a template with an XML element value of the match attribute is an XPath expression <xsl:value-of> element can be used to extract the value of an XML element and add it to the output stream of the transformation <xsl:for-each> element allows you to do looping in XSLT <xsl:sort> element is used to sort the output <xsl:if> element is used to put a conditional test against the content of the XML file <xsl:if test="price > 10"> <xsl:choose> element is used in conjunction with <xsl:when> and <xsl:otherwise> to express multiple conditional tests <xsl:apply-templates> element applies a template to the current element or to the current element's child nodes
93
Linking XSL to XML <?xml version="1.0" encoding="ISO "?> < xsl:stylesheet version="1.0" xmlns:xsl=" < xsl:template match="/"> <html> <body> <h2>My CD Collection</h2> <table border="1"> <tr bgcolor="#9acd32"> <th>Title</th> <th>Artist</th> </tr> <xsl:for-each select="catalog/cd"> <xsl:sort select="artist"/> <tr> <td><xsl:value-of select="title"/></td> <td><xsl:value-of select="artist"/></td> </tr> </xsl:for-each> </table> </body> </html> < /xsl:template> < /xsl:stylesheet> <?xml version="1.0" encoding="ISO "?> <?xml-stylesheet type="text/xsl" href="cdcatalog.xsl"?> < catalog> <cd> <title>Empire Burlesque</title> <artist>Bob Dylan</artist> <country>USA</country> <company>Columbia</company> <price>10.90</price> <year>1985</year> </cd> . < /catalog> <td><xsl:value-of select="title"/></td> <xsl:choose> <xsl:when test="price > 10"> <td bgcolor="#ff00ff"> <xsl:value-of select="artist"/></td> </xsl:when> <xsl:otherwise> <td><xsl:value-of select="artist"/></td> </xsl:otherwise> </xsl:choose>
94
XML Data Input Straight XML in SQL JDBC using special XMLType (also C)
INSERT VALUES( XMLType(‘<xml>goes here</xml>’)) JDBC using special XMLType (also C) SQL*Loader w/ direct path load mode XML-SQL Utility (XSU) Maps XML to columns Rigid default mapping No support for attributes
95
XML Database Storage Native XML type (Structured Storage)
Preserves textual fidelity Shreds into SQL tables Complete validation, full SQL support No triggers to update tables (built-in rewriting) Some overhead Cannot change schema w/o reloading all data Requires a schema Annotate XML schema to control nested collections storage, as: CLOB Array of serialized SQL objects Nested table of serialized SQL objects Array of XMLType
96
XQuery in Oracle XMLDB integrated database engine
SQL / XML standard support Optimized queries – rewrite to relational Standalone Java query engine 100% Java Integrated into Oracle App Server -XDS Interoperates with XSLT/XPath Supports XMLQuery and XMLTable construct Native compilation into SQL /XML structures Returns XMLType(Content) Can query over relational, O-R, XMLType data SQL*Plus provides xquery command to execute XQuery XSL-T will also get compiled to XQuery
97
Sample XQuery For each author in the bibliography, list the author's name and the titles of all books by that author, grouped inside a "result" element." <results> FOR $a IN distinct(document(" RETURN <result> $a, FOR $b IN document(" = $a] RETURN $b/title </result> </results> SELECT XMLELEMENT (NAME “order”, XMLATTRIBUTES (o.oid AS “id”), XMLELEMENT (NAME “signdate”, o.contractdate), XMLELEMENT (NAME “amount”, (SELECT SUM(orderitem) FROM orderItems AS oi WHERE i.oid o.oid) ) FROM orders AS o WHERE status ‘open’; <order id=“4711”> <signdate> </signdate> <amount>24000</amount> </order> <order id=“4712”> <signdate> </signdate>
98
XML Database Architecture
example XML enabled Apps Web Browser HTTP XML over HTTP HTTP GET or POST HTML over HTTP Delegated to XMLDataGateway XSL stylesheet JDBC2HTML servelet XLST In process call XML serialized resultset In process call XML serialized resultset JDBC2XML Class JDBC
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.