dw & adbms-22

197
M. Sc. Part I [INFORMATION TECHNOLOGY] Practical Journal [DATAWAREHOUSING AND MINING] Seat Number [ ] Department of Computer Science and Information Technology Deccan Education Society’s Kirti College of Arts, Science and Commerce. [ NAAC Accredited : “A Grade”]

Upload: api-26413529

Post on 11-Apr-2015

544 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: DW & ADBMS-22

M. Sc. Part I [INFORMATION TECHNOLOGY] Practical Journal [DATAWAREHOUSING AND MINING]

Seat Number [ ]

Department of Computer Science and Information Technology Deccan Education Society’s

Kirti College of Arts, Science and Commerce. [ NAAC Accredited : “A Grade”]

Page 2: DW & ADBMS-22

Department of Computer Science and Information Technology

Deccan Education Society’s Kirti College of Arts, Science and Commerce.

[ NAAC Accredited : “A Grade”]

C E R T I F I C A T E This is to certify that Mr./Miss ______________________

of M.Sc Part-I [COMPUTER SCIENCE] with Seat

No._______has successfully completed the practical of

Datawarehousing and Data Mining under my supervision in

this college during the year 2006 - 2007.

Lecturer-in-charge Head of Department (Mrs.Apurva Yadav) Dept of Com.Sc and I.T (Dr. Seema Purohit)

Page 3: DW & ADBMS-22

NAAC Accreditation “A” Grade

Deccan Education Society’s

Kirti M. Doongursee College, Dadar, Mumbai-28 Dept. of Computer Science & I.T.

M.Sc. (Part-I) 2006 – 07

PAPER IV (SECTION-I)

DATAWAREHOUSING AND DATA MINING

INDEX

No. Topic Page

No. Date Sign

1

Create a warehouse in MS SQL Server 2000 and import various databases from external sources such as Access/Excel/Text File by using Data Transformation Services (DTS) tool.

2

Create and schedule a DTS Package using Data Transformation services (DTS) tool. Fire at least 5 queries on the database

3 Create a Database using Analysis Manager and create a Single-Dimensional OLAP cube by using STAR schema.

4

Create a Database using Analysis Manager and create a Multi-Dimensional OLAP cube by using Snowflake schema

5 Create a Mining Model by using OLAP Data.

6 Create a Mining Model by using Relational Data.

Page 4: DW & ADBMS-22

Roll No. – 22 NAAC Accreditation “A” Grade

Deccan Education Society’s Kirti M. Doongursee College, Dadar, Mumbai-28

Dept. of Computer Science & I.T. M.Sc. (Part-I) 2006 – 07

Subject: Data Warehousing

Practical 01

Create a warehouse in MS SQL Server 2000 and import various databases from external sources such as Access/Excel/Text File by using Data Transformation Services (DTS) tool. STEP 1: Build OLTP SYSTEM

Page 5: DW & ADBMS-22

Steps in importing a database from Access Start->Program->MS SQL Server->Import and Export Data

Page 6: DW & ADBMS-22

Click <new> from drop down list of Database as shown above. Enter Database Name. Click Ok

Page 7: DW & ADBMS-22

Select the database ‘practdb’ from the Database dropdown list.Click Next.

Page 8: DW & ADBMS-22

Click Select All - Click Transform button near Customer table and check drop and recreate option as shown below.(Repeat this step for each table.)

Page 9: DW & ADBMS-22

Check Save DTS Package and Click Next Name your package as practdts. Click Next.

Page 10: DW & ADBMS-22

Click Finish.

Page 11: DW & ADBMS-22

Start Enterprise Manager Start->Programs ->Microsoft SQL Server->Enterprise Manager

Page 12: DW & ADBMS-22

Right click the DTS package practdts and select design package.

Steps in creating a fact table: 1. Select Microsoft OLEDB provider for SQL server from connection toolbox.

2. Select Microsoft Access from connection toolbox.

Page 13: DW & ADBMS-22

3. Select ‘Execute SQL task’ from Task toolbox.

a) Create Fact Table ->Click Build Query->Click Parse Query

3. Select ‘Execute SQL task’ from Task toolbox.

b) Drop Fact Table- Write Query for drop table as shown below->Click Parse Query

Page 14: DW & ADBMS-22

4. Transforming data from MS Access to SQL server

First Select Microsoft Access and then Select Transform Data Task from Task toolbox and drop it on FactConnection First Select Drop fact table and then Create Fact table Select from WorkFlow menu-on completion First Select create fact table task and then select Microsoft Access Select from WorkFlow menu -on success. Next double click the arrow pointing from Microsoft Access to Factconnection Click Build Query->Parse Query

Page 15: DW & ADBMS-22

DeSelect all the transformation

Page 16: DW & ADBMS-22
Page 17: DW & ADBMS-22

Click New-> Click Copy Column->Click OK

Page 18: DW & ADBMS-22

Select source column then select destination column that you want->click ok

Transformation Completed. Save the DTS package and execute the package.

Page 19: DW & ADBMS-22

BUILD A CUBE: Step1: Create a Database

Page 20: DW & ADBMS-22

Step2: Create a data source

Step 3: After creating datasource right click Cube option under your database ‘practdb’. Select New Cube-> Wizard

Page 21: DW & ADBMS-22

Click Next

Page 22: DW & ADBMS-22

How to add measures to the cube:

Measures are the quantitative values in the database that you want to analyze. Commonly-used measures are sales, cost, and budget data. Measures are analyzed against the different dimension categories of a cube.

1. To define the measures for your cube, under Fact table numeric columns, double-click store_sales. Repeat this procedure for the store_cost and unit_sales columns, and then click Next.

Click Next

Page 23: DW & ADBMS-22

How to build your Customer dimension:

1. Click New Dimension. 2. In the Welcome step, click Next. 3. In the Choose how you want to create the dimension step, select Star Schema: A single

dimension table, and then click Next.

Page 24: DW & ADBMS-22

4. In the Select the dimension table step, click Customer, and then click Next.

5. In the Select the dimension type step, click Next. 6. To define the levels for your dimension, under Available columns, double-click the

Country, State_Province, City, and lname columns, in that order. After you double-click

Page 25: DW & ADBMS-22

each column, its name appears under Dimension levels. After you have selected all four columns, click Next.

7. In the Specify the member key columns step, click Next.

8. In the Select advanced options step, click Next.

Page 26: DW & ADBMS-22

9. In the last step of the wizard, enter Customer in the Dimension name box, and leave the Share this dimension with other cubes box selected. Click Finish.

10. In the Cube Wizard, you should see the Customer dimension in the Cube dimensions list.

Page 27: DW & ADBMS-22

How to build your Product dimension:

1. Click New Dimension again. In the Welcome to the Dimension Wizard step, click Next. 2. In the Choose how you want to create the dimension step, select Snowflake Schema:

Multiple, related dimension tables, and then click Next. 3. In the Select the dimension tables step, double-click product and product_class to add

them to Selected tables. Click Next. 4. The two tables you selected in the previous step and the existing join between them are

displayed in the Create and edit joins step of the Dimension Wizard. Click Next.

5. To define the levels for your dimension, under Available columns, double-click the product_category, product_subcategory, and brand_name columns, in that order. After you double-click each column, its name appears under Dimension levels. Click Next after you have selected all three columns.

6. In the Specify the member key columns step, click Next. 7. In the Select advanced options step, click Next. 8. In the last step of the wizard, enter Product in the Dimension name box, and leave the Share

this dimension with other cubes box selected. Click Finish. 9. You should see the Product dimension in the Cube dimensions list.

How to build your Store dimension:

10. Click New Dimension again. In the Welcome to the Dimension Wizard step, click Next. 11. In the Choose how you want to create the dimension step, select Snowflake Schema:

Multiple, related dimension tables, and then click Next. 12. In the Select the dimension tables step, double-click store and promotion to add them to

Selected tables. Click Next.

Page 28: DW & ADBMS-22

13. The two tables you selected in the previous step and the existing join between them are displayed in the Create and edit joins step of the Dimension Wizard. Click Next.

14. To define the levels for your dimension, under Available columns, double-click the store country, store state, promotion name, store city, store name columns, in that order. After you double-click each column, its name appears under Dimension levels. Click Next after you have selected all three columns.

15. In the Specify the member key columns step, click Next. 16. In the Select advanced options step, click Next. 17. In the last step of the wizard, enter store in the Dimension name box, and leave the Share

this dimension with other cubes box selected. Click Finish. 18. You should see the store dimension in the Cube dimensions list.

How to build your Time dimension:

1. In the Select the dimensions for your cube step of the wizard, click New Dimension. This calls the Dimension Wizard.

2. In the Welcome step, click Next. 3. In the Choose how you want to create the dimension step, select Star Schema: A single

dimension table, and then click Next. 4. In the Select the dimension table step, click time_by_day. You can view the data contained

in the time_by_day table by clicking Browse Data. When you are finished viewing the time_by_day table, click Next.

5. In the Select the dimension type step, select Time dimension, and then click Next.

Page 29: DW & ADBMS-22

6. Next, you will define the levels for your dimension. In the Create the time dimension levels step, click Select time levels, click Year, Quarter, Month, and then click Next.

7. In the Select advanced options step, click Next. 8. In the last step of the wizard, enter Time for the name of your new dimension.

Note: You can designate whether this dimension will be shared or private using the Share this dimension with other cubes check box, which is located on the lower left corner of the screen. Leave the box selected.

9. Click Finish to return to the Cube Wizard.

10.In the Cube Wizard, you should now see the Time dimension in the Cube dimensions list.

How to finish building your cube:

1. In the Cube Wizard, click Next. 2. Click Yes when prompted by the Fact Table Row Count message.

Page 30: DW & ADBMS-22

3. In the last step of the Cube Wizard, name your cube Pract1Cube, and then click Finish. 4. The wizard closes and then launches Cube Editor, which contains the cube you just created.

By clicking on the blue or yellow title bars.

Page 31: DW & ADBMS-22

Save the cube editor

Page 32: DW & ADBMS-22

Design Storage and Process the Cube How to design storage by using the Storage Design Wizard

1. In the Analysis Manager tree pane, expand the Cubes folder, right-click the Sales cube, and then click Design Storage.

2. In the Welcome step, click Next. 3. Select MOLAP as your data storage type, and then click Next.

4. Under Set Aggregation Options, click Performance gain reaches. In the box, enter 40 to indicate the percentage.

You are instructing Analysis Services to give a performance boost of up to 40 percent, regardless of how much disk space this requires. Administrators can use this tuning ability to balance the need for query performance against the disk space required to store aggregation data.

5. Click Start. 6. You can watch the Performance vs. Size graph in the right side of the wizard while Analysis

Services designs the aggregations. Here you can see how increasing performance gain requires additional disk space utilization. When the process of designing aggregations is complete, click Next.

Page 33: DW & ADBMS-22

7. Under What do you want to do?, select Process now, and then click Finish. Note: Processing the aggregations may take some time.

8. In the window that appears, you can watch your cube while it is being processed. When processing is complete, a message appears confirming that the processing was completed successfully.

9. Click Close to return to the Analysis Manager tree pane.

Page 34: DW & ADBMS-22
Page 35: DW & ADBMS-22

METADATA:

Click On Data For Analysing

Page 36: DW & ADBMS-22

Roll No. – 22

NAAC Accreditation “A” Grade Deccan Education Society’s

Kirti M. Doongursee College, Dadar, Mumbai-28 Dept. of Computer Science & I.T.

M.Sc. (Part-I) 2006 – 07

Subject: Data Warehousing

Practical 02 Create and schedule a DTS Package using Data Transformation services (DTS) tool. Fire at least 5 queries on the database. BUILD OLTP SYSTEM

CREATE DATABASE: nw_mart

Create an empty nw_mart database in SQL Server.

Page 37: DW & ADBMS-22

OPEN SQL Query Analyzer

Start->Program->MS SQL Server->Query Analyzer

Click Ok In SQL Query Analyzer window CODE: (For Creating and Dropping Dimension tables) if exists (select * from sysobjects where id = object_id(N'[dbo].[Customer_Dim]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [dbo].[Customer_Dim] GO if exists (select * from sysobjects where id = object_id(N'[dbo].[Employee_Dim]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [dbo].[Employee_Dim] GO if exists (select * from sysobjects where id = object_id(N'[dbo].[Product_Dim]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [dbo].[Product_Dim] GO if exists (select * from sysobjects where id = object_id(N'[dbo].[Sales_Fact]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [dbo].[Sales_Fact] GO if exists (select * from sysobjects where id = object_id(N'[dbo].[Shipper_Dim]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [dbo].[Shipper_Dim] GO if exists (select * from sysobjects where id = object_id(N'[dbo].[Time_Dim]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [dbo].[Time_Dim] GO

Page 38: DW & ADBMS-22

CREATE TABLE [dbo].[Customer_Dim] ( [CustomerKey] [int] IDENTITY (1, 1) NOT NULL , [CustomerID] [nchar] (5) NOT NULL , [CompanyName] [nvarchar] (40) NOT NULL , [ContactName] [nvarchar] (30) NOT NULL , [ContactTitle] [nvarchar] (30) NOT NULL , [Address] [nvarchar] (60) NOT NULL , [City] [nvarchar] (15) NOT NULL , [Region] [nvarchar] (15) , [PostalCode] [nvarchar] (10) NULL , [Country] [nvarchar] (15) NOT NULL , [Phone] [nvarchar] (24) NOT NULL , [Fax] [nvarchar] (24) NULL )ON [PRIMARY] GO CREATE TABLE [dbo].[Employee_Dim] ( [EmployeeKey] [int] IDENTITY (1, 1) NOT NULL , [EmployeeID] [int] NOT NULL , [EmployeeName] [nvarchar] (30) NOT NULL , [HireDate] [datetime] NULL ) ON [PRIMARY] GO CREATE TABLE [dbo].[Product_Dim] ( [ProductKey] [int] IDENTITY (1, 1) NOT NULL , [ProductID] [int] NOT NULL , [ProductName] [nvarchar] (40) NOT NULL , [SupplierName] [nvarchar] (40) NOT NULL , [CategoryName] [nvarchar] (15) NOT NULL , [ListUnitPrice] [money] NOT NULL ) ON [PRIMARY] GO CREATE TABLE [dbo].[Sales_Fact] ( [TimeKey] [int] NOT NULL , [CustomerKey] [int] NOT NULL , [ShipperKey] [int] NOT NULL , [ProductKey] [int] NOT NULL , [EmployeeKey] [int] NOT NULL , [RequiredDate] [datetime] NOT NULL , [LineItemFreight] [money] NOT NULL , [LineItemTotal] [money] NOT NULL , [LineItemQuantity] [smallint] NOT NULL , [LineItemDiscount] [money] NOT NULL ) ON [PRIMARY] GO CREATE TABLE [dbo].[Shipper_Dim] ( [ShipperKey] [int] IDENTITY (1, 1) NOT NULL , [ShipperID] [int] NOT NULL , [ShipperName] [nvarchar] (40) NOT NULL ) ON [PRIMARY] GO CREATE TABLE [dbo].[Time_Dim] ( [TimeKey] [int] IDENTITY (1, 1) NOT NULL ,

Page 39: DW & ADBMS-22

[TheDate] [datetime] NOT NULL , [DayOfWeek] [nvarchar] (20) NOT NULL , [Month] [int] NOT NULL , [Year] [int] NOT NULL , [Quarter] [int] NOT NULL , [DayOfYear] [int] NOT NULL , [Holiday] [nvarchar] (1) NOT NULL , [Weekend] [nvarchar] (1) NOT NULL , [YearMonth] [nvarchar] (10) NOT NULL , [WeekOfYear] [int] NOT NULL ) ON [PRIMARY] GO

Explanation: sysobjects SQL Server sysobjects Table contains one row for each object created within a database. In other words, it has a row for every constraint, default, log, rule, stored procedure, and so on in the database. Therefore, this table can be used to retrieve information about the database. OBJECT_ID Returns the database object identification number. Syntax

OBJECT_ID ( 'object' )

Arguments

'object'

Is the object to be used. object is either char or nchar. If object is char, it is implicitly converted to nchar.

Return Types int UNICODE STRING

Unicode strings have a format similar to character strings but are preceded by an N identifier (N

stands for National Language in the SQL-92 standard). The N prefix must be uppercase. For example, 'Michél' is a character constant while N'Michél' is a Unicode constant. Unicode constants are interpreted as Unicode data, and are not evaluated using a code page. Unicode constants do have a collation, which primarily controls comparisons and case sensitivity. Unicode constants are assigned the default collation of the current database, unless the COLLATE clause is used to specify a collation. Unicode data is stored using two bytes per character, as opposed to one byte per character for character data.

Page 40: DW & ADBMS-22

In Microsoft SQL Server, these data types support Unicode data:

• nchar

• nvarchar

• ntext

Note The n prefix for these data types comes from the SQL-92 standard for National (Unicode) data types.

Use of nchar, nvarchar, and ntext is the same as char, varchar, and text, respectively

OBJECTPROPERTY

Returns information about objects in the current database.

Syntax

OBJECTPROPERTY ( id , property )

Arguments

id

Is an expression containing the ID of the object in the current database. id is int.

property

Is an expression containing the information to be returned for the object specified by id. property can be one of these values.

Note Unless noted otherwise, the value NULL is returned when property is not a valid property name.

Property name Object type Description and values returned

IsUserTable Table User-defined table.

1 = True 0 = False

Page 41: DW & ADBMS-22

IDENTITY (Property)

Creates an identity column in a table. This property is used with the CREATE TABLE and ALTER TABLE Transact-SQL statements.

Note The IDENTITY property is not the same as the SQL-DMO Identity property that exposes the row identity property of a column.

Syntax

IDENTITY [ ( seed , increment ) ]

Arguments

seed

Is the value that is used for the very first row loaded into the table.

increment

Is the incremental value that is added to the identity value of the previous row that was loaded.

You must specify both the seed and increment or neither. If neither is specified, the default is (1,1).

Page 42: DW & ADBMS-22

STEPS:

1.Save Query as Nwmartcreate.sql.

2.Execute the Nwmartcreate.sql script in SQL Server on the newly-created nw_mart database. This script will create the table and index structure for the sample database.

Create DTS package

3.Save the sample DTS package, NorthwindDTS.dts to SQL Server.

4.Run the DTS package by selecting Execute from the Package menu.

This will retrieves the data from the Northwind Database and populate the tables in newly created nw_mart Database.

Page 43: DW & ADBMS-22

To schedule the Package NorthwindDTS.dts

Right click NorthwindDTS.dts Package -> Schedule Package

Queries:

1. Show the total units sold for each product where the required data is earlier than today.

CODE:

SELECT Product_Dim.ProductName, Product_Dim.CategoryName,

Product_Dim.SupplierName,SUM(Sales_Fact.LineItemQuantity) AS

[Total Units Sold], Sales_Fact.RequiredDate FROM Sales_Fact

INNER JOIN Product_Dim ON

Sales_Fact.ProductKey = Product_Dim.ProductKey

GROUP BY Product_Dim.ProductName,

Product_Dim.CategoryName,

Product_Dim.SupplierName,

Sales_Fact.RequiredDate

HAVING (Sales_Fact.RequiredDate < getdate())

Page 44: DW & ADBMS-22

Output:

2. Show the Product name, Category name, Suppliers name,total units sold for each product where total unit sold is greater than 100 .

Code:

SELECT Product_Dim.ProductName, Product_Dim.CategoryName, Product_Dim.SupplierName, SUM(Sales_Fact.LineItemQuantity) AS [Total Units Sold], Sales_Fact.RequiredDate

FROM Sales_Fact INNER JOIN Product_Dim ON Sales_Fact.ProductKey = Product_Dim.ProductKey

GROUP BY Product_Dim.ProductName, Product_Dim.CategoryName, Product_Dim.SupplierName, Sales_Fact.RequiredDate, Sales_Fact.LineItemQuantity

HAVING (SUM(Sales_Fact.LineItemQuantity) >100)

Page 45: DW & ADBMS-22

Output:

3. To View Total Unit Sold Of All the Products Under the category whose average sale is greater than 50% SELECT Product_Dim.ProductName,

Product_Dim.CategoryName, SUM(Sales_Fact.LineItemQuantity) AS [Total Units Sold]

FROM Sales_Fact INNER JOIN Product_Dim ON Sales_Fact.ProductKey = Product_Dim.ProductKey

GROUP BY Product_Dim.Productkey, Product_Dim.ProductName, Product_Dim.CategoryName

HAVING (AVG(Sales_Fact.LineItemQuantity) >0.5) Output:

Page 46: DW & ADBMS-22

4. To View Company Name and Total Quantity sold for all the Products Code: SELECT Customer_Dim.CompanyName, Sum(Sales_Fact.LineItemQuantity) AS

TotalQtySold FROM Sales_Fact, Customer_Dim WHERE Sales_Fact.CustomerKey=Customer_Dim.CustomerKey GROUP BY Customer_Dim.CompanyName ORDER BY Sum(Sales_Fact.LineItemQuantity) DESC Output:

5. To view total Price of products sold by Employee to Company Code: SELECT Employee_Dim.EmployeeName, Product_Dim.ProductName,

Customer_Dim.CompanyName, Time_Dim.TheDate, Sales_Fact.LineItemTotal

FROM Time_Dim INNER JOIN (Product_Dim INNER JOIN (Employee_Dim INNER JOIN (Customer_Dim INNER JOIN Sales_Fact ON Customer_Dim.CustomerKey = Sales_Fact.CustomerKey) ON Employee_Dim.EmployeeKey = Sales_Fact.EmployeeKey) ON Product_Dim.ProductKey = Sales_Fact.ProductKey) ON Time_Dim.TimeKey = Sales_Fact.TimeKey;

Page 47: DW & ADBMS-22

Output:

Page 48: DW & ADBMS-22

Roll No. – 22

NAAC Accreditation “A” Grade Deccan Education Society’s

Kirti M. Doongursee College, Dadar, Mumbai-28 Dept. of Computer Science & I.T.

M.Sc. (Part-I) 2006 – 07

Subject: Data Warehousing

Practical 03

Create a Database using Analysis Manager and create a Single-Dimensional OLAP cube by using STAR schema. Set Up the System Data Source Connection: A data source contains the information necessary to access source data for an object. Why? Before you begin working with Analysis Manager, you must first set connections to the source of your data in the ODBC Data Source Administrator.

Page 49: DW & ADBMS-22

How to set up your system data source name (DSN)

1. Microsoft® Windows NT® 4.0 users: Click the Start button, point to Settings, click Control Panel, and then double-click Data Sources (ODBC).

Windows® 2000 users: Click the Start button, point to Settings, click Control Panel, double-click Administrative Tools, and then double-click Data Sources (ODBC).

2. On the System DSN tab, click Add. 3. Select Microsoft Access Driver (*.mdb), and then click Finish. 4. In the Data Source Name box, enter pract3DSN , and then under Database, click Select. 5. In the Select Database dialog box, browse C:\Program Files\Microsoft Analysis

Services\Samples, and then click FoodMart 2000.mdb. Click OK.

6. In the ODBC Microsoft Access Setup dialog box, click OK.

7. In the ODBC Data Source Administrator dialog box, click OK.

Page 50: DW & ADBMS-22

Start Analysis Manager: Analysis Manager is a snap-in program that runs on Microsoft® Management Console (MMC). How to start Analysis Manager

• Click the Start button, point to Programs, Microsoft SQL Server, and Analysis Services, and then click Analysis Manager.

Set Up the Database and Data Source: How to set up your database structure

1. In the Analysis Manager tree view, expand Analysis Servers. 2. Click the name of your server. A connection with the Analysis server will be established. 3. Right-click your server's name, and then click New Database. 4. In the Database dialog box, in the Database name box, enter pract3DW, and then click OK. 5. In the Analysis Manager tree pane, expand the server, and then expand the pract3DW

database you just created.

Next set up a connection to the sample data in the pract3DW data source.

How to set up your data source

1. In the Analysis Manager tree pane, right-click the Data Sources folder under the pract3DW database, and then click New Data Source.

2. In the Data Link Properties dialog box, click the Provider tab, and then click Microsoft OLE DB Provider for ODBC Drivers.

3. Click the Connection tab, and then from the Use data source name list, click pract3DSN. 4. Click Test Connection to be sure everything works. A message should appear in the

Microsoft Data Link dialog box, stating that your connection was successful. In the message box, click OK.

5. Click OK to close the Data Link Properties dialog box.

Build a Cube: How to open the Cube Wizard

• In the Analysis Manager tree pane, under the pract3DW database, right-click the Cubes folder, click to New Cube, and then click Wizard.

How to add measures to the cube

Measures are the quantitative values in the database that you want to analyze. Commonly-used measures are sales, cost, and budget data. Measures are analyzed against the different dimension categories of a cube.

1. In the Welcome step of the Cube Wizard, click Next. 2. In the Select a fact table from a data source step, and then click sales_fact_1998. 3. You can view the data in the sales_fact_1998 table by clicking Browse data. After you finish

browsing data, close the Browse data window, and then click Next. 4. To define the measures for your cube, under Fact table numeric columns, double-click

store_sales. Repeat this procedure for the store_cost and unit_sales columns, and then click Next.

Page 51: DW & ADBMS-22

How to build your Customer dimension

1. Click New Dimension. 2. In the Welcome step, click Next. 3. In the Choose how you want to create the dimension step, select Star Schema: A single

dimension table, and then click Next. 4. In the Select the dimension table step, click Customer, and then click Next. 5. In the Select the dimension type step, click Next. 6. To define the levels for your dimension, under Available columns, double-click the

Country, State_Province, City, and lname columns, in that order. After you double-click each column, its name appears under Dimension levels. After you have selected all four columns, click Next.

7. In the Specify the member key columns step, click Next. 8. In the Select advanced options step, click Next. 9. In the last step of the wizard, enter Customer in the Dimension name box, and leave the

Share this dimension with other cubes box selected. Click Finish. 10. In the Cube Wizard, you should see the Customer dimension in the Cube dimensions list.

How to finish building your cube

1. In the Cube Wizard, click Next. 2. Click Yes when prompted by the Fact Table Row Count message. 3. In the last step of the Cube Wizard, name your cube pract3CUBE, and then click Finish. 4. The wizard closes and then launches Cube Editor, which contains the cube you just created.

By clicking on the blue or yellow title bars, arrange the tables so that they match the following illustration.

Page 52: DW & ADBMS-22

Process the Cube:

1. Close the cube editor, go to Analysis Manager expand cube.

2. Right click pract3CUBE.

3. Select process option.

1. In the window that appears, you can watch your cube while it is being processed. When processing is complete, a message appears confirming that the processing was completed successfully.

2. Click Close to return to the Analysis Manager tree pane.

Page 53: DW & ADBMS-22

Browse Cube Data:

How to view cube data using Cube Browser

1. In the Analysis Manager tree pane, right-click the pract3CUBE cube, and then click Browse Data.

2. Cube Browser appears, displaying a grid made up of one dimension and the measures of your cube.

Page 54: DW & ADBMS-22

How to drill down

1. On Customer dimensions Double-click the cell in your grid that contains country canada. The cube expands to include the subcategory column.

Note: You can close the subcategory column by double-clicking a cell that has been expanded.

Use the above techniques to move dimensions to and from the grid.

When you are finished, click Close to close Cube Browser.

Page 55: DW & ADBMS-22

Roll No. – 22

NAAC Accreditation “A” Grade Deccan Education Society’s

Kirti M. Doongursee College, Dadar, Mumbai-28 Dept. of Computer Science & I.T.

M.Sc. (Part-I) 2006 – 07

Subject: Data Warehousing

Practical 04

1. Create a Database using Analysis Manager and create a Multi-Dimensional OLAP cube by

using Snowflake schema.

Set Up the System Data Source Connection

A data source contains the information necessary to access source data for an object.

Why?

Before you begin working with Analysis Manager, you must first set connections to the source of your data in the ODBC Data Source Administrator.

How to set up your system data source name (DSN)

6. Microsoft® Windows NT® 4.0 users: Click the Start button, point to Settings, click Control Panel, and then double-click Data Sources (ODBC).

Windows® 2000 users: Click the Start button, point to Settings, click Control Panel, double-click Administrative Tools, and then double-click Data Sources (ODBC).

7. On the System DSN tab, click Add. 8. Select Microsoft Access Driver (*.mdb), and then click Finish. 9. In the Data Source Name box, enter pract4DSN , and then under Database, click Select. 10. In the Select Database dialog box, browse C:\Program Files\Microsoft Analysis

Services\Samples, and then click FoodMart 2000.mdb. Click OK. 11. 6.In the ODBC Microsoft Access Setup dialog box, click OK. 12. 7.In the ODBC Data Source Administrator dialog box, click OK.

Start Analysis Manager

Analysis Manager is a snap-in program that runs on Microsoft® Management Console (MMC).

Page 56: DW & ADBMS-22

How to start Analysis Manager

• Click the Start button, point to Programs, Microsoft SQL Server, and Analysis Services, and then click Analysis Manager.

Set Up the Database and Data Source

How to set up your database structure

6. In the Analysis Manager tree view, expand Analysis Servers. 7. Click the name of your server. A connection with the Analysis server will be established. 8. Right-click your server's name, and then click New Database. 9. In the Database dialog box, in the Database name box, enter pract4DW, and then click OK. 10. In the Analysis Manager tree pane, expand the server, and then expand the pract4DW

database you just created.

Next set up a connection to the sample data in the pract4DW data source.

How to set up your data source

6. In the Analysis Manager tree pane, right-click the Data Sources folder under the pract4DW database, and then click New Data Source.

7. In the Data Link Properties dialog box, click the Provider tab, and then click Microsoft OLE DB Provider for ODBC Drivers.

8. Click the Connection tab, and then from the Use data source name list, click pract4DSN. 9. Click Test Connection to be sure everything works. A message should appear in the

Microsoft Data Link dialog box, stating that your connection was successful. In the message box, click OK.

10. Click OK to close the Data Link Properties dialog box.

Build a Cube

How to open the Cube Wizard

• In the Analysis Manager tree pane, under the pract4DW database, right-click the Cubes folder, click to New Cube, and then click Wizard.

How to add measures to the cube

Measures are the quantitative values in the database that you want to analyze. Commonly-used measures are sales, cost, and budget data. Measures are analyzed against the different dimension categories of a cube.

5. In the Welcome step of the Cube Wizard, click Next. 6. In the Select a fact table from a data source step, and then click sales_fact_1998. 7. You can view the data in the sales_fact_1998 table by clicking Browse data. After you finish

browsing data, close the Browse data window, and then click Next. 8. To define the measures for your cube, under Fact table numeric columns, double-click

store_sales. Repeat this procedure for the store_cost and unit_sales columns, and then click Next.

Page 57: DW & ADBMS-22

How to build your Product dimension

1. Click New Dimension again. In the Welcome to the Dimension Wizard step, click Next. 2. In the Choose how you want to create the dimension step, select Snowflake Schema:

Multiple, related dimension tables, and then click Next. 3. In the Select the dimension tables step, double-click product and product_class to add

them to Selected tables. Click Next. 4. The two tables you selected in the previous step and the existing join between them are

displayed in the Create and edit joins step of the Dimension Wizard. Click Next. 5. To define the levels for your dimension, under Available columns, double-click the

product_category, product_subcategory, and brand_name columns, in that order. After you double-click each column, its name appears under Dimension levels. Click Next after you have selected all three columns.

6. In the Specify the member key columns step, click Next. 7. In the Select advanced options step, click Next. 8. In the last step of the wizard, enter Product in the Dimension name box, and leave the Share

this dimension with other cubes box selected. Click Finish. 9. You should see the Product dimension in the Cube dimensions list.

How to build your Store dimension

1. Click New Dimension again. In the Welcome to the Dimension Wizard step, click Next. 2. In the Choose how you want to create the dimension step, select Snowflake Schema:

Multiple, related dimension tables, and then click Next. 3. In the Select the dimension tables step, double-click store and region to add them to

Selected tables. Click Next. 4. The two tables you selected in the previous step and the existing join between them are

displayed in the Create and edit joins step of the Dimension Wizard. Click Next. 5. To define the levels for your dimension, under Available columns, double-click the store

country,sales country,sales region,store state,salescity,store city columns, in that order. After you double-click each column, its name appears under Dimension levels. Click Next after you have selected all three columns.

6. In the Specify the member key columns step, click Next. 7. In the Select advanced options step, click Next. 8. In the last step of the wizard, enter Store in the Dimension name box, and leave the Share

this dimension with other cubes box selected. Click Finish. 9. You should see the Store dimension in the Cube dimensions list.

Page 58: DW & ADBMS-22

How to finish building your cube

1. In the Cube Wizard, click Next. 2. Click Yes when prompted by the Fact Table Row Count message. 3. In the last step of the Cube Wizard, name your cube Sales, and then click Finish. 4. The wizard closes and then launches Cube Editor, which contains the cube you just created.

By clicking on the blue or yellow title bars, arrange the tables so that they match the following illustration.

Process the Cube

1. Close the cube editor, go to Analysis Manager expand cube

2. Right click pract4CUBE

3. Select Process option.

Page 59: DW & ADBMS-22

1. In the window that appears, you can watch your cube while it is being processed. When processing is complete, a message appears confirming that the processing was completed successfully.

2. Click Close to return to the Analysis Manager tree pane.

Browse Cube Data

How to view cube data using Cube Browser

3. In the Analysis Manager tree pane, right-click the pract4CUBE cube, and then click Browse Data.

4. Cube Browser appears, displaying a grid made up of one dimension and the measures of your cube. The additional one dimensions appear at the top of the browser.

Page 60: DW & ADBMS-22

How to replace a dimension in the grid

1. To replace one dimension in the grid with another, drag the dimension from the top box and drop it directly on top of the column you want to exchange it with. Make sure the pointer appears with a double-ended arrow during this process.

2. Using this drag and drop technique, select the Store dimension button and drag it to the grid, dropping it directly on top of Measures. The Store and Measures dimensions will switch positions in Cube Browser.

Page 61: DW & ADBMS-22

3. When you are finished, click Close to close Cube Browser.

.

Page 62: DW & ADBMS-22

Roll No. – 22

NAAC Accreditation “A” Grade Deccan Education Society’s

Kirti M. Doongursee College, Dadar, Mumbai-28 Dept. of Computer Science & I.T.

M.Sc. (Part-I) 2006 – 07

Subject: Data Mining

Practical 05

Create a Mining Model by using Relational Data.

Create a Relational Data Mining Model Using Microsoft Decision Trees Scenario: The Marketing department is now getting familiar with data mining techniques. They realize the data warehouse contains a great deal of information that is not in the cube. They want to analyze this detailed information to find out whether it will reveal interesting facts about customers' buying behavior.

In this section you will create a relational mining model using the Microsoft Decision Trees algorithm to investigate the data warehouse data.

How to create a data mining model that discovers customer patterns

1. In the Analysis Manager tree pane, right-click the Mining Models folder, and then click New Mining Model.

2. The Mining Model Wizard opens. In the Welcome to the Mining Model Wizard step, click Next.

3. In the Select source type step, click Relational Data. Click Next.

Page 63: DW & ADBMS-22

4. In the Select case tables step, click A single table contains the data. In the Available tables box, select Customer. Click Next.

5. In the Select data mining technique step, in the Technique box, select Microsoft Decision Trees. Click Next.

Page 64: DW & ADBMS-22

6. In the Select the key column step, in the Case key column box, click customer_id. Click Next.

7. In the Select input and predictable columns step, select the following columns and successively move them to the Predictable columns box using the > button: marital_status, yearly_income, num_children_at_home, total_children, education, member_card, occupation, houseowner, num_cars_owned.

Page 65: DW & ADBMS-22

8. The same columns will also be used as input columns. Select the same columns and move them to the Input columns box by using the > button next to the Input column list. Click Next.

9. In the final step, in the Model Name box, enter Advanced customer patterns discovery. Ensure that Save and process now is selected. Click Finish.

Page 66: DW & ADBMS-22

10. The Process windows appears, showing your model being processed. When processing is complete, a message appears, stating "Processing completed successfully", click Close.

How to read the Customer decision tree

1. You are now in Relational Mining Model Editor. You can use this editor to edit properties of the model or to browse the result of it. Maximize the Relational Mining Model Editor.

2. Click the Content tab at the bottom of the right pane. 3. The decision tree for the Education characteristic appears. In the Data Mining Wizard, you

selected several columns from the relational table as input and predictable columns for the mining model. This meant that those columns were used to train the model and were also the target of the model to determine possible predictions. Consequently, the relational mining model generated one decision tree for each predictable column. Each decision tree is defined by nodes determined by the other columns. In the Education decision tree example, you can see that the two most important factors that predict the likelihood that the customer has a certain education level are his or her yearly income (defined by 1st level of the tree) and his or her occupation (defined by the 2nd level of the tree).

Page 67: DW & ADBMS-22

4. Now you have two main ways to investigate and navigate the tree further: You can double-click on nodes of the tree, or you can use the content navigator pane. You can see that the tree extends beyond the right edge of the editor. To access those invisible nodes, you can make one of the nodes in the branch that you investigate the new root of your current decision tree view. To do this, double-click the selected node. In this example, double-click Yearly Income = $30K - $50K. The decision tree makes this node the root of the current view and creates more space to display all its children.

Page 68: DW & ADBMS-22

5. You can see in the content navigator pane that the part of the tree currently displayed in the content detail pane is magnified. Now, move your mouse over the content navigator pane and click different locations. You can see that the decision tree magnifies what it displays in the content detail pane based on the position of your mouse. To return to the original tree pane, in the content navigator pane, move your mouse over the root of the tree and click on it to refresh the content detail pane.

Page 69: DW & ADBMS-22

6. To investigate other trees, in the Prediction Tree box, select Yearly Income. Its decision tree appears. You can see that this tree is much deeper and larger than the previous one. You can use the two navigation methods described in the previous step to navigate this tree.

7. In a similar way, select other characteristics in the Prediction Tree box and investigate the various characteristic patterns.

Page 70: DW & ADBMS-22

Roll No. – 22

NAAC Accreditation “A” Grade

Deccan Education Society’s Kirti M. Doongursee College, Dadar, Mumbai-28

Dept. of Computer Science & I.T. M.Sc. (Part-I) 2006 – 07

Subject: Data Mining

Practical 06

Create a Mining Model by using OLAP Data. Step 1: Create a database :pract6DM Step 2: Create a data source

Page 71: DW & ADBMS-22
Page 72: DW & ADBMS-22

Build a Cube

A cube is a multidimensional structure of data. Cubes are defined by a set of dimensions and measures.

How to open the Cube Wizard

• In the Analysis Manager tree pane, under the pract6DM database, right-click the Cubes folder, click to New Cube, and then click Wizard.

How to add measures to the cube

1. In the Welcome step of the Cube Wizard, click Next. 2. In the Select a fact table from a data source step, expand the pract6DM data source, and

then click sales_fact_1998. 3. You can view the data in the sales_fact_1998 table by clicking Browse data. After you finish

browsing data, close the Browse data window, and then click Next.

4. To define the measures for your cube, under Fact table numeric columns, double-click store_sales. Repeat this procedure for the store_cost and unit_sales columns, and then click Next.

Page 73: DW & ADBMS-22

How to build your Time dimension

1. In the Select the dimensions for your cube step of the wizard, click New Dimension. This calls the Dimension Wizard.

Page 74: DW & ADBMS-22
Page 75: DW & ADBMS-22
Page 76: DW & ADBMS-22

In the Select advanced options step, click Next.

How to build your Customer dimension

1. Click New Dimension. 2. In the Welcome step, click Next. 3. In the Choose how you want to create the dimension step, select Star Schema: A single

dimension table, and then click Next. 4. In the Select the dimension table step, click Customer, and then click Next. 5. In the Select the dimension type step, click Next. 6. To define the levels for your dimension, under Available columns, double-click the

Country, State_Province, City, and lname columns, in that order. After you double-click each column, its name appears under Dimension levels. After you have selected all four columns, click Next.

7. In the Specify the member key columns step, click Next. 8. In the Select advanced options step, click Next. 9. In the last step of the wizard, enter Customer in the Dimension name box, and leave the

Share this dimension with other cubes box selected. Click Finish. 10. In the Cube Wizard, you should see the Customer dimension in the Cube dimensions list.

Page 77: DW & ADBMS-22

How to build your Product dimension

1. Click New Dimension again. In the Welcome to the Dimension Wizard step, click Next. 2. In the Choose how you want to create the dimension step, select Snowflake Schema:

Multiple, related dimension tables, and then click Next. 3. In the Select the dimension tables step, double-click product and product_class to add

them to Selected tables. Click Next. 4. The two tables you selected in the previous step and the existing join between them are

displayed in the Create and edit joins step of the Dimension Wizard. Click Next.

5. To define the levels for your dimension, under Available columns, double-click the product_category, product_subcategory, and brand_name columns, in that order. After you double-click each column, its name appears under Dimension levels. Click Next after you have selected all three columns.

6. In the Specify the member key columns step, click Next. 7. In the Select advanced options step, click Next. 8. In the last step of the wizard, enter Product in the Dimension name box, and leave the Share

this dimension with other cubes box selected. Click Finish. 9. You should see the Product dimension in the Cube dimensions list.

Page 78: DW & ADBMS-22

How to build your Store dimension

1. Click New Dimension. 2. In the Welcome step, click Next. 3. In the Choose how you want to create the dimension step, select Star Schema: A single

dimension table, and then click Next. 4. In the Select the dimension table step, click Store, and then click Next. 5. In the Select the dimension type step, click Next. 6. To define the levels for your dimension, under Available columns, double-click the

store_country, store_state, store_city, and store_name columns, in that order. After you double-click each column, its name will appear under Dimension levels. After you have selected all four columns, click Next.

7. In the Specify the member key columns step, click Next. 8. In the Select advanced options step, click Next. 9. In the last step of the wizard, enter Store in the Dimension name box, and leave the Share

this dimension with other cubes box selected. Click Finish. 10. In the Cube Wizard, you should see the Store dimension in the Cube dimensions list.

How to finish building your cube

1. In the Cube Wizard, click Next. 2. Click Yes when prompted by the Fact Table Row Count message.

Page 79: DW & ADBMS-22

In the last step of the Cube Wizard, name your cube pract6cube, and then click Finish.

Page 80: DW & ADBMS-22

Cube Editor

Edit a Cube

You can make changes to your existing cube by using Cube Editor.

How to edit your cube in Cube Editor You can use two methods to get to Cube Editor:

1.In the Analysis Manager tree pane, right-click an existing cube, and then click Edit.

2.Create a new cube using Cube Editor directly. This method is not recommended unless you are an advanced user.

In the schema pane of Cube Editor, the fact table (with yellow title bar) and the joined dimension tables (blue title bars) are seen. In the Cube Editor tree pane, you can preview the structure of your cube in a hierarchical tree. You can edit the properties of the cube by clicking the Properties button at the bottom of the left pane.

Page 81: DW & ADBMS-22

How to add a dimension to an existing cube

At this point, you decide you need a new dimension to provide data on product promotions. You can easily build this dimension in Cube Editor.

NOTE: Dimensions built in Cube Editor are, by default, private dimensions; that is, they can be used only with the cube you are working on and cannot be shared with other cubes. They do not appear in the Shared Dimensions folder in the Analysis Manager tree view. When creating such a dimension through the Dimension Wizard, you can make it shared across cubes.

1. In Cube Editor, on the Insert menu, click Tables. 2. In the Select table dialog box, click the promotion table, click Add, and then click

Close. 3. To define the new dimension, double-click the promotion_name column in the

promotion table. 4. In the Map the Column dialog box, select Dimension, and then click OK.

Page 82: DW & ADBMS-22

5. Select the Promotion Name dimension in the tree view. 6. On the Edit menu, click Rename. 7. Type Promotion, and then press ENTER. 8. Save your changes. 9. Close Cube Editor. When prompted to design the storage, click No

Design Storage and Process the Cube

You can design storage options for the data and aggregations in your cube. Before you can use or browse the data in your cubes, you must process them.

How to design storage by using the Storage Design Wizard

1. In the Analysis Manager tree pane, expand the Cubes folder, right-click the pract6cube, and then click Design Storage.

2. In the Welcome step, click Next. 3. Select MOLAP as your data storage type, and then click Next. 4. Under Set Aggregation Options, click Performance gain reaches. In the box, enter 40 to

indicate the percentage.

You are instructing Analysis Services to give a performance boost of up to 40 percent, regardless of how much disk space this requires. Administrators can use this tuning ability to balance the need for query performance against the disk space required to store aggregation data.

5. Click Start. 6. You can watch the Performance vs. Size graph in the right side of the wizard while Analysis

Services designs the aggregations. Here you can see how increasing performance gain requires additional disk space utilization. When the process of designing aggregations is complete, click Next.

Page 83: DW & ADBMS-22

7. Under What do you want to do?, select Process now, and then click Finish. Note: Processing the aggregations may take some time.

8. In the window that appears, you can watch your cube while it is being processed. When processing is complete, a message appears confirming that the processing was completed successfully.

9. Click Close to return to the Analysis Manager tree pane.

Browse Cube Data

Now you're ready to browse the data in the pract6cube cube!

How to view cube data using Cube Browser

1. In the Analysis Manager tree pane, right-click the pract6cube, and then click Browse Data. 2. Cube Browser appears, displaying a grid made up of one dimension and the measures of your

cube. The additional four dimensions appear at the top of the browser.

Page 84: DW & ADBMS-22

Build a Cube with Parent-Child Dimensions

A parent-child dimension is an organized hierarchy of members that is defined by its parent-child relationships. Often it does not have a symmetrical number of levels for each of its branches.

Why?

Parent-child dimensions are often used for describing employees or relationships between geographical areas. They can be used to represent charts of accounts (Profit & Loss, Balance Sheet, and so on). In some cases, Products or Customer dimensions can also be organized in a nonsymmetrical way. The parent-child schema is used in a relational database for this type ofdimension: one column represents the children, and another represents the parents.

Scenario: Now the Sales cube is built. The HR department heard about this new analysis tool and wants to analyze employee salary by store.

In this section you will build an HR cube for employee salary analysis. You will create the employee dimension as a parent-child dimension. Then you will use it, as well as regular dimensions, to generate the HR cube.

Page 85: DW & ADBMS-22

How to open the Dimension Wizard for Analysis Manager

1. In the Analysis Manager tree pane, under the pract6DM database, right-click the Shared Dimensions folder, click New Dimension, and then click Wizard.

How to build your Employee dimension

1. In the Welcome step, click Next. 2. In the Choose how you want to create the dimension step, select Parent-Child: Two

related columns in a single dimension table, and then click Next. 3. In the Select the dimension table step, click employee, and then click Next. 4. To define the child column, next to Member key, select employee_id. To define the parent

column, next to Parent key, select supervisor_id. To define the Member name column, next to Member name, select full_name. Click Next.

5. In the Select advanced options step of the wizard, click Next. 6. In the final step, enter Employee in the Dimension name box. Click Finish. 7. You are now in Dimension Editor. On the File menu, click Exit to close Dimension Editor. 8. You should see the Employee dimension in the Shared dimensions list.

Page 86: DW & ADBMS-22

How to build the HR cube

1. In the Analysis Manager tree pane, under the pract6DM database, right-click the Cubes folder, click New Cube, and then click Wizard.

2. Follow the steps in the wizard to create an HR cube with the following characteristics: 1. Fact table: salary 2. Measures: salary_paid, vacation_used 3. Dimensions: Employee, Store, Time 4. Count fact table rows? Yes

3. In the last step of the wizard, name your cube HR, and then click Finish. 4. Cube Editor appears. To manually create the joins, drag the the_date field of the

time_by_day table onto the pay_date field in the salary table. 5. Click the store_id field in the store table and drag it onto the store_id field in the employee

table.

Page 87: DW & ADBMS-22

6. Remove the department_id join that was automatically created between the salary table and the employee table: Select the join by clicking on it, and then press Delete.

7. When this is complete, close Cube Editor. Click Yes when you are prompted to save the cube, but click No when you are prompted to design the storage.

Create a Calculated Member

You can create customized measures or dimension members, called calculated members, by combining cube data or by using arithmetic operators, numbers, and/or functions.

Why?

You can use calculated members to enhance your analysis by modeling the raw data into meaningful business indicators. Calculated members increase the value of your analysis. They can outline trends, behaviors, and exceptions

Scenario: Now the Sales cube is populated with data. The Marketing department wants to enhance the pract6cube data and determine the average product price of the products sold at each store.

Page 88: DW & ADBMS-22

How to create a calculated member

1. In the Analysis Manager tree pane, under the pract6DM database, right-click the pract6cube, and then click Edit.

2. You are now editing the pract6cube in Cube Editor. The cube components (dimensions, measures, calculated members...) are listed in the left pane of Cube Editor.

3. Right-click Calculated Members, and then click New Calculated Member. 4. You are now in Calculated Member Builder. The first three boxes determine the dimension's

characteristics of the calculated member: Parent dimension (the dimensions to which it belongs), Parent member (the parent under which it is attached), and Member name.

Page 89: DW & ADBMS-22

5. Leave Parent dimension set to Measures. The Parent Member box is unavailable because the measure dimension does not support hierarchies. In the Member name box, enter Average price.

6. The lower part of Calculated Member Builder provides all the components necessary for building the calculated member expression. Under Data, expand the Measures dimension, and then expand MeasuresLevel. The list of measures appears.

7. Select Store Sales, and then drag it into the Value expression box. 8. In the number and operator pad, click the / operator. The operator appears at the end of the

expression in the Value expression box. 9. Under Data, select the Unit sales measure and drag it to the end of the expression in the

Value expression box.

Page 90: DW & ADBMS-22

10. The calculated member is now completely defined. Click OK. Calculated Member Builder closes and you are back in Cube Editor. Notice that the newly created calculated member is now available in the Calculated Members folder in the left pane of Cube Editor.

Page 91: DW & ADBMS-22

11. Save your changes by clicking the Save icon or by clicking Save on the File menu.

How to view calculated member data

Calculated members are calculated on the fly. This means that the data resulting from the calculated member expression is never stored; it is calculated every time the calculated member is requested in an analysis.

1. To view data, click the Data tab at the bottom of the right pane. The data appears, with the Measures dimension in columns and the Customer dimension in rows. Notice that four columns appear: the three measures and the calculated member you just created, Average Price.

Page 92: DW & ADBMS-22

2.

3. Close Cube Editor.

Create Member Properties

A member property is an attribute of a dimension member. It provides end users with additional information about the member.

Why?

Member properties have a variety of uses. In addition to providing information about a member, member properties can be used in queries and thus provide end users with more options when analyzing cube data. Member properties can also be the basis of levels in virtual dimensions

Scenario: The Marketing department wants to extend the pract6cube analysis capabilities to analyze customers sales data based on their characteristics: gender, marital status, education, yearly income, number of children at home, and membership card.

In this section you will add six member properties to the Customer dimension: gender, marital status, education, yearly income, number of children at home, and membership card. These member properties will qualify each member of the Customer dimension.

Page 93: DW & ADBMS-22

How to create Member Properties

1. In the Analysis Manager tree pane, expand the Shared Dimensions folder. 2. Right-click the Customer dimension, and then click Edit. 3. In Dimension Editor, expand Lname. You will see the Member Properties folder for the

level. 4. In the schema pane, drag the gender column from the Customer table to the Member

Properties folder for LName.

5. Repeat the previous step for the following five columns: marital_status, education, yearly_income, num_children_at_home, and member_card. You should see six member properties under Lname in the Member Properties folder: Gender, Marital Status, Education, Yearly Income, Num Children At Home, and Member Card.

Page 94: DW & ADBMS-22

6. On the File menu, click Save. 7. Close Dimension Editor.

Create a Virtual Dimension

A virtual dimension is a logical dimension based on the contents of a physical dimension. These contents can be either existing member properties in the physical dimension or columns in the tables of the physical dimension.

Why?

Using virtual dimensions, you can analyze cube data based on the member properties of the dimension members in a cube. The benefit is that this type of dimension does not consume disk space or processing time.

Scenario:

Now that you have added six member properties to the Customers dimension, you will create a virtual dimension with the Yearly Income member property and then add this newly created dimension to the pract6cube.

Page 95: DW & ADBMS-22

How to create a virtual dimension

1. In the Analysis Manager tree pane, right-click the Shared Dimensions folder, point to New Dimension, and then click Wizard.

2. In the Welcome step of the Dimension Wizard, click Next. 3. Select Virtual Dimension: The member properties of another dimension, and then click

Next. 4. In the Select the dimension with the member properties step, click the Customer

dimension, and then click Next.

5. In the Select the levels for the virtual dimension step, click the Lname.Yearly Income member property, and then click the add (>) button. Click Next.

6. In the Select advanced options step, make sure that no items in the Options box are checked. You will not need to set these advanced options at this time. Click Next.

7. In the Finish the Dimension Wizard step, in the Dimension Name box, enter Yearly Income.

8. Click Finish. 9. You are now in Dimension Editor. On the File menu, click Exit. 10. The new dimension is included in list of shared dimensions.

How to add a virtual dimension to an existing cube

1. In the Analysis Manager tree view, right-click the pract6cube in the Cubes folder, and then click Edit.

2. In Cube Editor, right-click Dimensions in the left pane tree. Click Existing Dimensions.

Page 96: DW & ADBMS-22

3. In Dimension Manager, select the newly created dimension, Yearly Income, and drag it to the Cube dimensions list. Click OK.

Page 97: DW & ADBMS-22

4. Close Cube Editor. Click Yes when prompted to save the cube. 5. Click Yes when prompted by the Design Storage window. 6. Follow the Storage Design Wizard steps and select the following settings:

1. Data storage type: MOLAP 2. Aggregation options: Performance gain reaches 20% 3. Final step: Process the cube

7. Click Close in the Process dialog box when the last line reads: "Processing completed successfully".

Create an OLAP Data Mining Model Using Microsoft Decision Trees

A data mining model is a model that contains all the settings necessary to run a specific data mining task.

How to create a data mining model that discovers customer patterns

1. In the Analysis Manager tree view, expand the Cubes folder, right-click the pract6cube, then select New Mining Model.

2. The Mining Model Wizard opens. In the Select data mining technique step, in the Technique box, select Microsoft Decision Trees. Click Next.

Page 98: DW & ADBMS-22

3. In the Select case step, select Customer in the Dimension box. In the Level box, ensure that Lname is selected. Click Next.

Page 99: DW & ADBMS-22

4. In the Select predicted entity step, select A member property of the case level. Then, in the Member properties box, select Member Card.

5. Click Next. 6. In the Select training data step, scroll to the Customer dimension and clear the Country,

State Province, and City boxes (we don't need to determine customer patterns with aggregated level but at the individual customer level only). Click Next.

7. In the Create a dimension and virtual cube (optional) step, enter Customer Patterns in the Dimension name box. Then, in the Virtual cube name box, enter Trained Cube. Click Next.

8. In the final step, type Customer patterns discovery in the Model name field. Ensure that Save and Process now is selected. Click Finish.

Page 100: DW & ADBMS-22

9. A window appears that shows your model being processed. When processing is complete, a message appears, stating "Processing completed successfully", click Close.

How to read the Customer decision tree

1. You are now in OLAP Mining Model Editor. You can use this editor to edit properties of the model or to browse the result of it. Maximize the OLAP Mining Model Editor.

2. In the right pane, the decision tree is displayed. It is composed of 4 panes. The content detail pane (1) in the middle represents the portion of the decision tree on which the focus is set. The content navigator pane (2) represents the complete view of the tree. It enables you to set the focus to a different part of the tree. The two other panes provide attributes information (3) that can be seen with numeric values (with the Totals tab) or graphically (with the Histogram tab) and the node path area (4) related to the node that has the focus.

Page 101: DW & ADBMS-22

3. In the decision tree area of the content detail pane, the color represents the density of Cases (in our case: density of customers). The darker it is, the more cases are contained in the node. Click on the All node. It is black because it represents 100% of the (7632) cases. 7632 represents the number of customers that were active in 1998 (customers who have transactions recorded in the Sales cube). This also shows that not all customers were active during 1998, because we only have 7632 cases out of the 9991 customers contained in the Lname level of the Customer dimension.

4. The attributes pane shows that for the All node, 55.83% of all cases, or 4263 cases, are likely to select the Bronze card; 11.50% to select the Golden card; 23.32% to select the Normal card and 9.34% to select the Silver card. The Probability column in the Totals panel of the attributes pane can be resized if percentage is not shown.

5. These percentages change if you select different nodes of the tree. Let's try to investigate which customers are likely to select the golden card. To do this, we will redraw the tree to outline the high density of golden cards. In the lower right hand side, select Golden in the Tree color based on field. The tree now shows a different pattern of colors. We can see that the Customer.Lname.Yearly Income = $150K+ node has a higher density that any other node.

Page 102: DW & ADBMS-22

1. Double-click the Customer.Lname.Yearly Income = $150K+ node. The tree now displays only the sub-tree beneath the Customer.Lname.Yearly Income = $150K+ node. Select the Customer.Lname.Marital Status = M node. In the node path pane, you can see the complete characteristics definition of the customer contained in this node: customers whose income is higher than $150K+ and who are married. The attributes pane now shows that a higher percentage (81.05%) of customers than in the previous level (45.09%) are likely to select the Golden card.

1. You can look at other branches of the tree and investigate how likely a customer is to select one card over another. The Marketing department can use this information to determine the characteristics of customers who are most likely to select a specific type of card. Based on these characteristics (income, number of children, marital status, and so on), the card services and programs can be redefined to better fit their customers.

2. When you are finished analyzing the decision tree, close OLAP Mining Model Editor.

Page 103: DW & ADBMS-22

Department of Computer Science and Information Technology Deccan Education Society’s

Kirti College of Arts, Science and Commerce. [ NAAC Accredited : “A Grade”]

C E R T I F I C A T E

This is to certify that Mr./Miss______________________

of M.Sc Part-I [COMPUTER SCIENCE] with Seat

No._______has successfully completed the practical of

Advance Database Management System under my supervision

in this college during the year 2006 - 2007.

Lecturer-in-charge Head of Department (Mrs.Apurva Yadav) Dept of Com.Sc and I.T (Dr. Seema Purohit)

Page 104: DW & ADBMS-22

NAAC Accreditation “A” Grade

Deccan Education Society’s

Kirti M. Doongursee College, Dadar, Mumbai-28 Dept. of Computer Science & I.T.

M.Sc. (Part-I) 2006 – 07

PAPER IV (SECTION-II)

ADVANCED DATABASE MANAGEMENT SYSTEM

INDEX

No. Title Page No. Date Sign

1 Introduction to SQL

2 Distributed Database

3 Object Oriented Database

4 Active Database

5 Temporal Database

6 Spatial Database

7 XML Database

8 Multimedia Database

Page 105: DW & ADBMS-22

Roll No. – 22

NAAC Accreditation “A” Grade Deccan Education Society’s

Kirti M. Doongursee College, Dadar, Mumbai-28 Dept. of Computer Science & I.T.

M.Sc. (Part-I) 2006 – 07

Subject: ADBMS

Practical No.1

Revision to SQL

1. Basic Queries of SQL.

a. Create the table empno number (4) ename varchar2 (15) job varchar2 (15) join_date date salary Number (6)

2. Alter the table column Salary 3. Insert the 10 records 4. Update the 2 records 5. Select the records 6. Use the following functions

AVG( ), MIN, MAX, CEIL, FLOOR, MOD ( ), POWER ( ).

Page 106: DW & ADBMS-22

Practical No:1 Revision to SQL Create table Query:-

create table emp(empno number(4), ename varchar2(15), job varchar2(15) ,join_date date, salary number(6));

Alter table :- SQL> select * from emp; EMPNO ENAME JOB JOIN_DATE SALARY --------- --------------- --------------- --------- --------- 3 Kiran Manager 18-APR-83 36024 4 Raja Manager 03-APR-83 40000 5 Sayali DBA 01-NOV-84 20000 6 Reshma Accountant 21-NOV-84 15000 7 Kaustubh Tester 28-SEP-83 18000 8 Sunil Tester 24-OCT-81 12000 9 Saurbi Clerk 05-OCT-83 10000 10 Deepa Programmer 15-AUG-79 21000 8 rows selected. SQL> alter table emp add dept_no number(3); Table altered. SQL> select * from emp; EMPNO ENAME JOB JOIN_DATE SALARY DEPT_NO --------- --------------- --------------- --------- --------- -------------- 3 Kiran Manager 18-APR-83 36024 4 Raja Manager 03-APR-83 40000 5 Sayali DBA 01-NOV-84 20000 6 Reshma Accountant 21-NOV-84 15000 7 Kaustubh Tester 28-SEP-83 18000 8 Sunil Tester 24-OCT-81 12000 9 Saurbi Clerk 05-OCT-83 10000 10 Deepa Programmer 15-AUG-79 21000 9 rows selected. SQL> alter table emp drop column dept_no; Table altered.

Page 107: DW & ADBMS-22

SQL> select * from emp; EMPNO ENAME JOB JOIN_DATE SALARY --------- --------------- --------------- --------- --------- 3 Kiran Manager 18-APR-83 36024 4 Raja Manager 03-APR-83 40000 5 Sayali DBA 01-NOV-84 20000 6 Reshma Accountant 21-NOV-84 15000 7 Kaustubh Tester 28-SEP-83 18000 8 Sunil Tester 24-OCT-81 12000 9 Saurbi Clerk 05-OCT-83 10000 10 Deepa Programmer 15-AUG-79 21000 9 rows selected. SQL> Insert Query :-

insert into emp values(3,'Kiran','Manager','18-Apr-1983',35000); insert into emp values(4,'Raja','Manager','03-Apr-1983',40000); insert into emp values(5,'Sayali','DBA','1-Nov-1984',30000); insert into emp values(6,'Reshma','Accountant','21-Nov-1984',15000); insert into emp values(7,'Kaustubh','Tester','28-Sep-1983',18000); insert into emp values(8,'Sunil','Tester','24-Oct-1981',12000); insert into emp values(9,'Saurbi','Clerk','05-Oct-1983',10000); insert into emp values(10,'Deepa','Programmer','15-Aug-1979',21000); Select Query:- SQL> select * from emp; EMPNO ENAME JOB JOIN_DATE SALARY --------- --------------- --------------- --------- --------- 3 Kiran Manager 18-APR-83 35000 4 Raja Manager 03-APR-83 40000 5 Sayali DBA 01-NOV-84 30000 6 Reshma Accountant 21-NOV-84 15000 7 Kaustubh Tester 28-SEP-83 18000 8 Sunil Tester 24-OCT-81 12000 9 Saurbi Clerk 05-OCT-83 10000 10 Deepa Programmer 15-AUG-79 21000 8 rows selected. Update Query:- update emp set salary=20000 where ename='Sayali'; Select Query :- SQL> select * from emp where ename=’Sayali’;

Page 108: DW & ADBMS-22

EMPNO ENAME JOB JOIN_DATE SALARY --------- --------------- ---------- ----------------- -------------- 5 Sayali DBA 01-NOV-84 20000

Function :- AVG():-

SQL> select avg(salary) from emp;

AVG(SALARY) -----------

20600 MIN():- select min(salary) from emp;

MIN(SALARY) -----------

10000 MAX():- select max(Salary) from emp;

MAX(SALARY) -----------

40000 MOD():- SQL> select * from emp where mod(salary,7)=0; EMPNO ENAME JOB JOIN_DATE SALARY

--------- --------------- --------------- --------- --------- 3 Kiran Manager 18-APR-83 35000 10 Deepa Programmer 15-AUG-79 21000 POWER():- SQL> update emp set salary=salary+power(2,10) where empno=3; 1 row updated. SQL> select * from emp where empno=2; EMPNO ENAME JOB JOIN_DATE SALARY --------- --------------- --------------- --------- ---------

3 Kiran Manager 18-APR-83 36024

Page 109: DW & ADBMS-22

FLOOR():- SQL> select floor(15.7) from dual;

FLOOR(15.7) -----------

15

CEIL():- SQL> select ceil(15.7) from dual;

CEIL(15.7) ----------

16

Page 110: DW & ADBMS-22

Roll No. – 22

NAAC Accreditation “A” Grade Deccan Education Society’s

Kirti M. Doongursee College, Dadar, Mumbai-28 Dept. of Computer Science & I.T.

M.Sc. (Part-I) 2006– 07

Subject: ADBMS

Practical No.2

2.1 1. For the following global conceptual schema, divide the schema into Horizontal fragments

and place them on different nodes. Implement at least 5 suitable queries on these fragments that will demonstrate distributed databases environment.

We are given the following three relations with their keys underlined: Supplier( Sno,Sname,City,State) Part( Pno,Pname,Color) Supplier-Part( Sno,Pno,Qty). We know that Suppliers can supply many Parts and many Suppliers can supply a Part. Assume the Supplier table is horizontally fragmented using the predicates: State = Maharashtra State = Karnataka. We can also assume that Suppliers are evenly located in only those two states. In addition, the Part table is horizontally fragmented using the predicates: 1 � Pno �100, 101 � Pno � 200. Part numbers are continuous from 1 to 500, inclusive. Fragment the Supplier- Part relation according to your choice horizontally. Implement at least 5 suitable queries using oracle 8i/9i.

Page 111: DW & ADBMS-22

2. For a given a global conceptual schema, divide the schema into vertical fragments and

place them on different nodes. Implement at least 5 suitable queries on these fragments that will demonstrate distributed databases environment.

Assume we have a global conceptual schema that contains the following table with the key underlined: Employee(Eno,Ename,Job,Dno,Dname,Location). Also assume that we vertical fragment the table as follows: Employee (Eno; Ename; Job; Dno) Department (Dno; Dname; Location) In addition, assume we have 2 nodes/sites that contain the following fragments:

Site1/Node1 has Employee

Site2/Node2 has Department Implement at least 5 suitable queries using oracle 8i/9i on Employee fragments. 3. Place the replication of global conceptual schema on different nodes and implement

at least 5 suitable queries that will demonstrate distributed databases environment. Assume a schema Student ( Rollno, Name, Std, Marks) When you insert, update delete the record in one node then at the same time this action will

be fired on another node.

Page 112: DW & ADBMS-22

Practical No:2 Distributed Database

HORIZONTAL FRAGEMENTATION Create the table Supplier in oracle9i create table supplier9i(sno number(3),sname varchar2(30), city varchar2(20),state varchar2(20)) / Insert the atleast 10 records in Supplier table that is in oracle9i insert into supplier9i values(&sno,'&sname','&city','&state'); SQL> select * from supplier9i; SNO SNAME CITY STATE ----- ---------- ---------- ------------ 1 Ashwini Mumbai MH 2 Supriya Vasai MH 3 Shilpa Thane MH 4 Pallavi Dadar MH 5 Aditya Vasai MH 6 Sandesh Parel MH 7 Saurabh Virar MH 8 Samadhan Worli MH 9 Jayesh Thane MH 10 Amit Byculla MH 10 rows selected. Create the table Part in oracle9i create table part9i(pno number(3),pname varchar2(30), color varchar2(20)) / Table created.

Page 113: DW & ADBMS-22

Insert the atleast 10 records in Part table that is in oracle9i insert into part9i values (&pno,'&pname','&color'); SQL> select * from part9i; PNO PNAME COLOR --------- ---------- ------ 11 cpu silver 12 floppy pink 13 monitor white 14 keyboard black 15 mouse blue 16 web camera blue 6 rows selected. Create the table Supplier_Part in oracle9i SQL>create table supplier_part9i(sno number(3),pno number(3), qty number(5)) / Insert the atleast 10 records in Supplier_Part table that is in oracle9i SQL>insert into supplier_part9i values (&sno,&pno,&qty); SQL> select * from supplier_part9i order by sno; SNO PNO QTY ------- --------- --------- 1 16 20 2 14 55 3 12 24 4 12 45 5 13 41 6 17 40 7 12 34 8 14 22 9 11 20 10 11 34 10 rows selected.

Page 114: DW & ADBMS-22

Create the table Supplier in oracle8i create table supplier8i(sno number(3),sname varchar2(30), city varchar2(20),state varchar2(20)) / Insert the atleast 10 records in Supplier table that is in oracle8i insert into supplier8i values(&sno,'&sname','&city','&state'); SQL> select * from supplier8i; SNO SNAME CITY STATE ------- ---------- ---------- ------------ 11 niraj thane mp 12 yogesh thane mp 13 swapnil worli mp 14 sachin dadar mp 15 salil chembur mp 16 saloni mumbai mp 17 snehal borivali mp 18 kamini dahisar mp 19 Ratna Vasai mp 20 Ramesh Vasai mp 10 rows selected. SQL> insert into part8i values(&pno,'&pname','&color'); SQL> select * from part8i; PNO PNAME COLOR --------- ---------- ---------- 200 floppy white 201 pendrive white 202 cpu black 203 lancard black 204 touchpad red 205 cdrom white 6 rows selected.

Page 115: DW & ADBMS-22

Create the table Supplier_Part in oracle8i create table supplier_part8i(sno number(3),pno number(3), qty number(5)) / insert into supplier_part8i values (&sno,&pno,&qty); SQL> select * from supplier_part8i order by pno; SNO PNO QTY ------- ------- ------- 204 11 12 202 12 25 203 13 28 201 14 15 201 15 20 203 16 36 201 17 40 205 18 30 203 19 20 205 20 50 10 rows selected. Display the names of all the supplier from both state SQL> select s.sname,e.sname from supplier9i s,msc26.supplier8i@oracle8i e where s.sno=e.sno; SNAME SNAME ---------- ---------- Ashwini niraj Supriya yogesh Silpa swapnil Pallavi sachin Aditya salil Sandesh saloni Saurabh snehal samadhan kamini jayesh Ratna amit Ramesh 10 rows selected.

Page 116: DW & ADBMS-22

SQL> select sno from supplier9i 2 union 3 select sno from msc26.supplier8i@oracle8i; SNO --------- 1 2 3 4 5 6 7 8 9 10 10 rows selected. SQL> select sno from supplier9i 2 intersect 3 select sno from msc26.supplier8i@oracle8i; SNO --------- 1 2 3 4 5 6 7 8 9 10 10 rows selected.

Page 117: DW & ADBMS-22

SQL> select sname from supplier9i 2 union all 3 select sname from msc26.supplier8i@oracle8i; SNAME ---------- Ashwini Supriya Silpa Pallavi Aditya Sandesh Saurabh samadhan jayesh amit niraj yogesh swapnil sachin salil saloni snehal kamini Ratna Ramesh 20 rows selected. SQL> select s.sno,s.sname,p.pname,sp.qty from supplier9i s,part9i p, supplier_part9i sp where 2 s.sno=sp.sno and p.pno=sp.pno; SNO SNAME PNAME QTY -------- ---------- ------------ --------- 1 Ashwini web camera 20 2 Supriya keyboard 55 3 Silpa floppy 24 4 Pallavi floppy 45 5 Aditya monitor 41 7 Saurabh floppy 34 8 samadhan keyboard 22 9 jayesh cpu 20 10 amit cpu 34 9 rows selected.

Page 118: DW & ADBMS-22

SQL> select s.sno,s.sname,p.pname,sp.qty from supplier9i s,part9i p, supplier_part9i sp where 2 s.sno=sp.sno and p.pno=sp.pno 3 union 4 select s.sno,s.sname,p.pname,sp.qty from msc26.supplier8i@oracle8i s, 5 msc26.part8i@oracle8i p, msc26.supplier_part8i@oracle8i sp where 6 s.sno=sp.sno and p.pno=sp.pno; SNO SNAME PNAME QTY ----- ---------- ----------- --------- 1 Ashwini web camera 20 1 niraj cpu 12 2 Supriya keyboard 55 3 Silpa floppy 24 3 swapnil touchpad 28 4 Pallavi floppy 45 4 sachin floppy 15 5 Aditya monitor 41 5 salil floppy 20 6 saloni touchpad 36 7 Saurabh floppy 34 7 snehal floppy 40 8 kamini cdrom 30 8 samadhan keyboard 22 9 Ratna touchpad 20 9 jayesh cpu 20 10 Ramesh cdrom 50 10 amit cpu 34 18 rows selected. Total qty available in both states select sum(s.qty),sum(e.qty) from supplier_Part9i s,scott.supplier_part8i@oracle8i e where s.sno=e.sno select pname,sum(qty) from part9i,supplier_part9i where part9i.pno=supplier_part9i.pno group by pname

VERTICAL FRAGEMENTATION SQL> create table emp(empno number(5),ename varchar2(20),job varchar2(15),deptno number(4)); Table created.

Page 119: DW & ADBMS-22

SQL> / Enter value for empno: 1 Enter value for ename: 'Sandesh' Enter value for job: 'CEO' Enter value for deptno: 10 old 1: insert into emp values(&empno,&ename,&job,&deptno) new 1: insert into emp values(1,'Shilpa','CEO',10) 1 row created. SQL> / Enter value for empno: 2 Enter value for ename: 'Pallavi' Enter value for job: 'Md' Enter value for deptno: 10 old 1: insert into emp values(&empno,&ename,&job,&deptno) new 1: insert into emp values(2,'Pallavi','Md',10) 1 row created. SQL> / Enter value for empno: 3 Enter value for ename: 'Ashwini' Enter value for job: 'Md' Enter value for deptno: 10 old 1: insert into emp values(&empno,&ename,&job,&deptno) new 1: insert into emp values(3,'Ashwini','Md',10) 1 row created. SQL> / Enter value for empno: 4 Enter value for ename: 'Supriya' Enter value for job: 'Ceo' Enter value for deptno: 10 old 1: insert into emp values(&empno,&ename,&job,&deptno) new 1: insert into emp values(4,'Supriya','Ceo',10) 1 row created. SQL> / Enter value for empno: 5 Enter value for ename: 'Aditya' Enter value for job: 'Agm' Enter value for deptno: 20 old 1: insert into emp values(&empno,&ename,&job,&deptno) new 1: insert into emp values(5,'Aditya','Agm',20) 1 row created.

Page 120: DW & ADBMS-22

SQL> / Enter value for empno: 6 Enter value for ename: 'Saurabh' Enter value for job: 'Gm' Enter value for deptno: 20 old 1: insert into emp values(&empno,&ename,&job,&deptno) new 1: insert into emp values(6,'Saurabh','Gm',20) 1 row created. SQL> / Enter value for empno: 7 Enter value for ename: 'Samadhan' Enter value for job: 'Clerk' Enter value for deptno: 20 old 1: insert into emp values(&empno,&ename,&job,&deptno) new 1: insert into emp values(7,'Samadhan','Clerk',20) 1 row created. SQL> / Enter value for empno: 8 Enter value for ename: 'Ram' Enter value for job: 'Peon' Enter value for deptno: 20 old 1: insert into emp values(&empno,&ename,&job,&deptno) new 1: insert into emp values(8,'Ram','Peon',20) 1 row created. SQL> / Enter value for empno: 9 Enter value for ename: 'Shayam' Enter value for job: 'Security' Enter value for deptno: 10 old 1: insert into emp values(&empno,&ename,&job,&deptno) new 1: insert into emp values(9,'Shayam','Security',10) 1 row created. SQL> / Enter value for empno: 10 Enter value for ename: 'Gopal' Enter value for job: 'Md' Enter value for deptno: 20 old 1: insert into emp values(&empno,&ename,&job,&deptno) new 1: insert into emp values(10,'Gopal','Md',20) 1 row created.

Page 121: DW & ADBMS-22

SQL> select * from emp; EMPNO ENAME JOB DEPTNO ---------- ----------- ----------- -------------- 1 Sandesh Ceo 10 2 Pallavi Md 10 3 Ashwini Md 10 4 Supriya Ceo 10 5 Aditya Agm 20 6 Saurabh Gm 20 7 Samadhan Clerk 20 8 Ram Peon 20 9 Shayam Security 10 10 Gopal Md 20 10 rows selected. SQL> conn msc01/msc01@oracle8i connected. SQL> create table dept(deptno number(4),dname varchar2(20),location varchar2(20)); table created. SQL> insert into dept values(&deptno,&dname,&location); Enter value for deptno: 10 Enter value for dname: 'Accounting' Enter value for location: 'Mumbai' old 1: insert into dept values(&deptno,&dname,&location) New 1: insert into dept values(10,'Accounting','Mumbai') 1 row created. SQL> / Enter value for deptno: 20 Enter value for dname: 'Research' Enter value for location: 'Jalgaon' old 1: insert into dept values(&deptno,&dname,&location) New 1: insert into dept values(20,'Research','Jalgaon') 1 row created. SQL> / Enter value for deptno: 30 Enter value for dname: 'Sales' Enter value for location: 'Pune' Old 1: insert into dept values(&deptno,&dname,&location) New 1: insert into dept values(30,'Sales','Pune') 1 row created.

Page 122: DW & ADBMS-22

SQL> / Enter value for deptno: 40 Enter value for dname: 'Operation' Enter value for location: 'Nashik' Old 1: insert into dept values(&deptno,&dname,&location) New 1: insert into dept values(40,'Operation','Nashik') 1 row created. SQL> select * from dept; DEPTNO DNAME LOCATION ---------- --------------- ----------------- 10 Accounting Mumbai 20 Research Jalgaon 30 Sales Pune 40 Operation Nashik SQL> conn msc01/msc01@oracle9i connected. SQL> conn msc01/msc01@oracle8i Connected. SQL> grant all on dept to public with grant option; Grant succeeded. SQL> conn msc01/msc01@oracle9i Connected. SQL> select e1.empno, e1.ename, e1.job, e1.deptno, e2.dname, e2.location from emp e1,msc01.dept@oracle8i e2 where e1.deptno = e2.deptno; EMPNO ENAME JOB DEPTNO DNAME LOCATION 1 Sandesh Ceo 10 Accounting Mumbai 2 Pallavi Md 10 Accounting Mumbai 3 Ashwini Md 10 Accounting Mumbai 4 Supriya Ceo 10 Accounting Mumbai 5 Aditya Agm 20 Research Jalgaon 6 Saurabh Gm 20 Research Jalgaon 7 Samadhan Clerk 20 Research Jalgaon 8 Ram Peon 20 Research Jalgaon 9 Shyam Security 10 Accounting Mumbai 10 Gopal Md 20 Research Jalgaon

Page 123: DW & ADBMS-22

SQL> select e1.ename,dept.dname from emp e,msc01.dept@oracle8i dept where e1.dname = dept.dname; ENAME DNAME --------------- -------------------- Sandesh Accounting Pallavi Accounting Ashwini Accounting Supriya Accounting Aditya Research Saurabh Research Samadhan Research Ram Research Shayam Accounting Gopal Research 10 rows selected. SQL> update msc01.dept@oracle8i d set d.dname='Sales'where d.dname='Accounting'; 1 row updated. SQL> select ename,dept.dname from emp,msc01.dept@oracle8i where emp.deptno=dept.deptno; ENAME DNAME -------------------- -------------------- Shilpa Sales Pallavi Sales Ashwini Sales Shayam Sales Supriya Sales Aditya Research Saurabh Research Samadhan Research Gopal Research Ram Research 10 rows selected. SQL> update emp e set e.job='Ceo'where e.deptno=10; 5 rows updated. SQL> select * from emp; EMPNO ENAME JOB DEPTNO --------- -------------------- --------------- ------------ 1 Shilpa Ceo 10 2 Pallavi Ceo 10 3 Ashwini Ceo 10 4 Supriya Ceo 10 5 Aditya Agm 20 6 Saurabh Gm 20

Page 124: DW & ADBMS-22

7 Samadhan Clerk 20 8 Ram Peon 20 9 Shayam Ceo 10 10 Gopal Md 20 10 rows selected.

REPLICA Create the table Student9i (Rollno, Name, Std) in oracle 9i Create table Student9i ( rollno number(5), name varchar2(20), std varchar2(20) ) Create the table Student8i (Rollno, Name, Std) in oracle 8i Create table Student8i ( rollno number(5), name varchar2(20), std varchar2(20) ) Write the trigger for inserting the record in student8i table if you insert the record in student9i table. create trigger insertStudent after insert on student9i for each row BEGIN insert into msc26.student8i@oracle8i values(:new.roll,:new.name); END; Write the trigger for updatingthe record in student8i table if you update the record in student9i table. create trigger updateStudName after update of name on student9i for each row begin update msc26.student8i@oracle8i e set e.name=:new.name where e.roll=:old.roll; end; Write the trigger for deletinging the record in student8i table if you delete the record in student9i table. create trigger deleteStud after delete on student9i for each row begin delete from msc26.student8i@oracle8i e where e.roll=:old.roll; end;

Page 125: DW & ADBMS-22

Insert the 10 record in student9i table Insert into student9i values( &rollno,&’name’,&’std’) Select the record in student9i table Select * from student9i; Select the record in student8i table Select * from msc26.student8i@oracle8i;

Page 126: DW & ADBMS-22

Practical No:2 Distributed Database

2.2 Create a global conceptual schema Emp(Eno;Ename;Address;Email;Salary) and insert 10 records. Divide Emp into vertical fragments Emp1(Eno;Ename;Address)and Emp2(Eno;Email;Salary)on two different nodes. Fire the following queries: (i) Find the salary of an employee where employee number is known. (ii) Find the Email where the employee name is known. (iii) Find the employee name and Email where employee number is known. (iv) Find the employee name whose salary is > 2000. Fragmenting the distributed database schemas and apply queries on them In Vertical fragmentation we will consider the Emp table. Nodes used : Server1(msccs03) and Server2(msccs26) Structure of emp table:-

EMP(On msccs03) Field Data Type Eno Number(5)

Ename Varchar2(10) Address Varchar2(20) Email Varchar2(20) Salary Number(7,2)

Sql>Create table emp(eno number(5),ename varchar2(15),address varchar2(20), email varchar2(20),salary number(7,2)); Insertion of Records in table EMP (10 records) Queries : Insert into emp values(1,'john','mumbai','[email protected]',2000); Insert into emp values(2,'joe','delhi','[email protected]',4000); Insert into emp values(3,'smith',' kolkata','[email protected]',6000); . . . Insert into emp values(10,'james','jaipur','[email protected]',20000);

Page 127: DW & ADBMS-22

Sql>Select * From Emp;

Eno Ename Address Email Salary

1 John Mumbai [email protected] 2000 2 Joe Delhi [email protected] 4000 3 Smith Kolkata [email protected] 6000 4 Peter Chennai [email protected] 8000 5 Brian Mangalore [email protected] 10000 6 Justin Hyderabad [email protected] 12000 7 Francis Baroda [email protected] 14000 8 Alex Ooty [email protected] 15000 9 William Panaji [email protected] 16000 10 James Jaipur [email protected] 20000

Prerequisite:

Create net service name to both the servers msccs03 msccs26

Create Database links to Connect Database. DD3

Create public database link DD3 connect to scott identified by tiger using 'msccs03'; DD26

Create public database link DD26 connect to scott identified by tiger using 'msccs26'; Vertical Fragmentation: Vertically fragment the emp table using the following query: • Table EMPV1 at Msccs03 server: Sql> Create table EMPV1 as select Eno,Ename,Address from emp;

EMPV1 (On msccs03) Field Data Type Eno Number(5)

Ename Varchar2(15) Address Varchar2(20)

Page 128: DW & ADBMS-22

Sql> Select * From Empv1;

ENO ENAME ADDRESS 1 John Mumbai 2 Joe Delhi 3 Smith Kolkata 4 Peter Chennai 5 Brian Mangalore 6 Justin Hyderabad 7 Francis Baroda 8 Alex Ooty 9 William Panaji 10 James Jaipur

• Table EMPV2 at Msccs26 server: Sql> Create table EMPV2 as select Eno,Email,Salary from emp@DD3;

Sql> Select * From Empv2;

ENO EMAIL SALARY 1 [email protected] 2000 2 [email protected] 4000 3 [email protected] 6000 4 [email protected] 8000 5 [email protected] 10000 6 [email protected] 12000 7 [email protected] 14000 8 [email protected] 15000 9 [email protected] 16000 10 [email protected] 20000

EMPV2 (On msccs26) Field Data Type Eno Number(5)

Email Varchar2(20) Salary Number(7,2)

Page 129: DW & ADBMS-22

Final Queries: (i) Find the salary of an employee where employee number is known. Sql> Select e1.ename,e2.salary from empv1 e1, empv2@DD26 e2

where e1.eno=e2.eno;

ENAME SALARY

John 2000 Joe 4000

Smith 6000 Peter 8000 Brian 10000 Justin 12000 Francis 14000

Alex 15000 William 16000 James 20000

(ii) Find the Email where the employee name is known Sql> Select e1.ename,e2.email from empv1 e1, empv2@DD26 e2 where e1.ename='john' and e1.eno=e2.eno;

ENAME EMAIL

John [email protected] (iii) Find the employee name and Email where employee number is known. Sql> Select e1.ename,e2.email from empv1 e1,empv2@DD26 e2 where e2.eno=4 and e1.eno=4;

ENAME EMAIL Peter [email protected]

Page 130: DW & ADBMS-22

(iv) Find the employee name whose salary is > 2000. Sql> Select e1.ename,e2.salary from empv1 e1, empv2@DD26 e2 where e2.salary > 2000 and e1.eno=e2.eno;

ENAME SALARY Joe 4000

Smith 6000 Peter 8000 Brian 10000 Justin 12000 Francis 14000

Alex 15000 William 16000 James 20000

Page 131: DW & ADBMS-22

Practical No:2 Distributed Database

2.3 Create a global conceptual schema Emp(Eno;Ename;Address;Email;Salary) and insert 10 records.Divide Emp into horizontal fragments using the condition that Emp1 contains the tuples with salary ≤ 10,000 and Emp2 with 10,000< salary ≤ 20,000 on two different nodes. Fire the following queries: (i) Find the salary of all employees. (ii) Find the Email of all employees where salary = 15,000 (iii) Find the employee name and Email where employee number is known. (iv) Find the employee name and address where employee number is known. Fragmenting the distributed database schemas and apply queries on them In Horizontal fragmentation, we will consider the Emp table.

EMP(On msccs03) Field Data Type Eno Number(5)

Ename Varchar2(10) Address Varchar2(20) Email Varchar2(20) Salary Number(7,2)

Sql> Select * from Emp; ENO ENAME ADDRESS EMAIL SALARY

1 John Mumbai [email protected] 2000 2 Joe Delhi [email protected] 4000 3 Smith Kolkata [email protected] 6000 4 Peter Chennai [email protected] 8000 5 Brian Mangalore [email protected] 10000 6 Justin Hyderabad [email protected] 12000 7 Francis Baroda [email protected] 14000 8 Alex Ooty [email protected] 15000 9 William Panaji [email protected] 16000 10 James Jaipur [email protected] 20000

• Table EMPH1 at Msccs03 server:- Sql> Create table emph1 as select * from emp where salary <= 10000;

Page 132: DW & ADBMS-22

Sql> Select * From emph1;

ENO ENAME ADDRESS EMAIL SALARY

1 John Mumbai [email protected] 2000

2 Joe Delhi [email protected] 4000

3 Smith Kolkata [email protected] 6000

4 Peter Chennai [email protected] 8000

5 Brian Mangalore [email protected] 10000 • Table EMPH2 at Msccs26 server:- Sql> Create table emph2 as select * from emp@dd3 e1 where e1.salary > 10000 and e1.salary <=20000; Sql> Select * from emph2;

ENO ENAME ADDRESS EMAIL SALARY

6 Justin Hyderabad [email protected] 12000

7 Francis Baroda [email protected] 14000

8 Alex Ooty [email protected] 15000

9 William Panaji [email protected] 16000

10 James Jaipur [email protected] 20000

Queries: (i) Find the salary of all employees Sql> Select e1.ename,e1.salary from emph1 e1 union select e2.ename,e2.salary from emph2@DD26 e2;

ENAME SALARY Alex 15000

Brian 10000

Francis 14000

James 20000

Joe 4000

John 2000

Justin 12000

Peter 8000

Smith 6000

William 16000

Page 133: DW & ADBMS-22

(ii) Find the Email of all employees where salary = 15,000. Sql> Select e1.ename,e1.email from emph1 e1 where e1.salary=15000 union Select e2.ename,e2.email from emph2@DD26 e2 where e2.salary=15000;

ENAME EMAIL Alex [email protected]

(iii) Find the employee name and Email where employee number is known. Sql> Select e1.ename,e1.email from emph1 e1 where e1.eno=3 union select e2.ename,e2.email from emph2@DD26 e2 where e2.eno=3;

ENAME EMAIL Smith [email protected]

(iv) Find the employee name and address where employee number is known Sql> Select e1.ename,e1.address from emph1 e1 where e1.eno=3 union Select e2.ename,e2.address from emph2@DD26 e2 where e2.eno=3;

ENAME ADDRESS Smith Kolkata

Page 134: DW & ADBMS-22

Practical No:2 Distributed Database

2.4 Create a global conceptual schema Emp(Eno;Ename;Address;Email;Salary) and insert 10 records. Store the replication of Emp into two different nodes and fire the following queries: (i) Find the salary of all employees. (ii) Find the Email of all employees where salary = 15,000 (iii) Find the employee name and Email where employee number is known. (iv) Find the employee name and address where employee number is known. Nodes used: Server1(msccs03) and Server2(msccs26) Structure of emp table:

EMP(On msccs03) Field Data Type Eno Number(5)

Ename Varchar2(10) Address Varchar2(20) Email Varchar2(20) Salary Number(7,2)

Sql> Create table emp(eno number(5),ename varchar2(15),address varchar2(20),email varchar2(20),salary number(7,2)); Insertion of Records in table EMP (10 records) Queries : Insert into emp values(1,'john','mumbai','[email protected]',2000); Insert into emp values(2,'joe','delhi','[email protected]',4000); Insert into emp values(3,'smith',' kolkata','[email protected]',6000); . . . Insert into emp values(10,'james','jaipur','[email protected]',20000); Sql> Select * From Emp;

Eno Ename Address Email Salary

1 John Mumbai [email protected] 2000 2 Joe Delhi [email protected] 4000 3 Smith Kolkata [email protected] 6000 4 Peter Chennai [email protected] 8000 5 Brian Mangalore [email protected] 10000 6 Justin Hyderabad [email protected] 12000 7 Francis Baroda [email protected] 14000 8 Alex Ooty [email protected] 15000 9 William Panaji [email protected] 16000 10 James Jaipur [email protected] 20000

Page 135: DW & ADBMS-22

Similarly, create table Emp_Replica on Server2(msccs26). Prerequisite:

Create net service name to both the servers msccs03 msccs26

Create Microsoft ODBC DSN names using the Net Service names. replicadsn03 replicadsn26

Implement the viewing of the records stored on remote system.

Screen Layouts

(i) Find the salary of all employees.

Page 136: DW & ADBMS-22

(ii) Find the Email of all employees where salary = 15,000

Here Server1 is down and Server2 is up.

(iii) Find the employee name and Email where employee number is known.

Page 137: DW & ADBMS-22

(iv) Find the employee name and address where employee number is known.

If both Servers are down then the following message is displayed:

Page 138: DW & ADBMS-22

Code for the implementation of the above operations. Private Sub cmd_Click(Index As Integer) Select Case Index Case 0 query = "Select Salary from Emp" Case 1 query = "Select Email from Emp where Salary=15000" Case 2 If txt(0).Text = "" Then MsgBox "Please Provide An Employee No.", vbExclamation, "Eh??" txt(0).SetFocus Exit Sub End If query = "Select Ename,Email from Emp where Eno=" & txt(0).Text Case 3 If txt(1).Text = "" Then MsgBox "Please Provide An Employee No.", vbExclamation, "Eh??" txt(1).SetFocus Exit Sub End If query = "Select Ename,Address from Emp where Eno=" & txt(1).Text Case 4 Unload Me Exit Sub End Select Call Connect1 End Sub Public Sub Connect1() On Error GoTo Err: Call DestroyConn(conn1) With conn1 .Open "replicadsn03", "scott", "tiger" recset1.CursorLocation = adUseClient Call GetConnection(query, conn1, recset1, True) If recset1.RecordCount = 0 Then GoTo Err: dgrid.Caption = "Using Server 1" Call FillGrid(recset1) End With Exit Sub Err: Call Connect2 End Sub

Page 139: DW & ADBMS-22

Public Sub Connect2() On Error GoTo Err: Call DestroyConn(conn2) With conn2 .Open "replicadsn26", "scott", "tiger" recset2.CursorLocation = adUseClient Call GetConnection(query, conn2, recset2, True) If recset2.RecordCount = 0 Then MsgBox "There Are No Records..", vbExclamation, "Eh?" End If dgrid.Caption = "Using Server 2" Call FillGrid(recset2) End With Exit Sub Err: MsgBox "Error In Connection..." & vbCrLf & "Either The Servers Are Down Or The Following Error Has Occured:" & vbCrLf & "[" & Err.Number & "] " & Err.Description, vbCritical, "Error In Connection!!" End Sub Public Sub GetConnection(query As String, ByRef conn As ADODB.Connection, ByRef rec_set As ADODB.Recordset, readOnly As Boolean) If rec_set.State = adStateOpen Then rec_set.Close If readOnly Then rec_set.Open query, conn, adOpenKeyset Else rec_set.Open query, conn, adOpenKeyset, adLockOptimistic End If End Sub Public Sub DestroyConnection(ByRef rec_set As ADODB.Recordset) If rec_set.State = adStateOpen Then rec_set.Close Set rec_set = Nothing End Sub Public Sub DestroyConn(ByRef conn As ADODB.Connection) If conn.State = adStateOpen Then conn.Close Set conn = Nothing End Sub Private Sub FillGrid(rec_set As ADODB.Recordset) Set dgrid.DataSource = rec_set lbl(1).Caption = query & ";" lbl(3).Caption = rec_set.RecordCount End Sub

Page 140: DW & ADBMS-22

Roll No. – 22

NAAC Accreditation “A” Grade Deccan Education Society’s

Kirti M. Doongursee College, Dadar, Mumbai-28 Dept. of Computer Science & I.T.

M.Sc. (Part-I) 2006 – 07

Subject: ADBMS

Practical No.3

Object Oriented Database 3.1 Create your own data type “ person”: that includes attributes (first name, last name, dob)

& methods( getage). Define the related “people” table for the above-mentioned data

type by adding at least 10 records. Construct the queries for the above table:

1. To insert the records

2. To update the records

3. To select the records

4. To delete the records

Page 141: DW & ADBMS-22

Practical No:3 Object Oriented Database Create table Query:- SQL> create table people(per person); Table created. Create Type Query:- SQL> create or replace type person as 2 object(firstname varchar(20), 3 lastname varchar(20), 4 dob date, 5 member function getage return number); 6 / Type created. ------------------------------------------------------------------------------------------------------------ SQL> create or replace type body person as 2 member function getage return number as 3 begin 4 return floor(months_between(SYSDATE,dob)/12); 5 end getage; 6 end; 7 / Type body created. Insert Query :- insert into people values (person('sayli','nimkar','1-Nov-1983')); insert into people values (person('kiran','tawde','18-Apr-1983')); insert into people values (person('chandralata','paneria','21-Oct-1983')); insert into people values (person('aniket','sawant','29-Apr-1984')); insert into people values (person('nehal','paneria','28-Jul-1985'));

Page 142: DW & ADBMS-22

Select Query :- SQL> select p.per.firstname,p.per.lastname,p.per.dob,p.per.getage() as age from people p; PER.FIRSTNAME PER.LASTNAME PER.DOB AGE -------------------- ------------------------ ------------- --------- sayli nimkar 01-NOV-83 22 kiran tawde 18-APR-83 22 chandralata paneria 21-OCT-83 22 aniket sawant 29-APR-84 21 nehal paneria 28-JUL-85 20 Update Query:- SQL> select p.per.firstname,p.per.lastname,p.per.dob,p.per.getage() as age from people p; PER.FIRSTNAME PER.LASTNAME PER.DOB AGE -------------------- -------------------- ------------ ---------

sayli nimkar 01-NOV-83 22 kiran tawde 18-APR-83 22 chandralata paneria 21-OCT-83 22 aniket sawant 29-APR-84 21 nehal paneria 28-JUL-85 20

SQL> update people p set p.per.lastname='Kanitkar' where p.per.Firstname='sayli'; 1 row updated. SQL> select p.per.firstname,p.per.lastname,p.per.dob,p.per.getage() as age from people p; PER.FIRSTNAME PER.LASTNAME PER.DOB AGE -------------------- -------------------- --------------- ---------

sayli Kanitkar 01-NOV-83 22 kiran tawde 18-APR-83 22 chandralata paneria 21-OCT-83 22 aniket sawant 29-APR-84 21 nehal paneria 28-JUL-85 20

Delete Query:- SQL> select p.per.firstname,p.per.lastname,p.per.dob,p.per.getage() as age from people p; PER.FIRSTNAME PER.LASTNAME PER.DOB AGE -------------------- ------------------------ --------------- ---------

sayli Kanitkar 01-NOV-83 22 kiran tawde 18-APR-83 22 chandralata paneria 21-OCT-83 22 aniket sawant 29-APR-84 21 nehal paneria 28-JUL-85 20

SQL> delete from people p where p.per.Firstname='sayli'; 1 row deleted.

Page 143: DW & ADBMS-22

SQL> select p.per.firstname,p.per.lastname,p.per.dob,p.per.getage() as age from people p; PER.FIRSTNAME PER.LASTNAME PER.DOB AGE -------------------- -------------------- ---------------- --------- kiran tawde 18-APR-83 22 chandralata paneria 21-OCT-83 22 aniket sawant 29-APR-84 21 nehal paneria 28-JUL-85 20

Page 144: DW & ADBMS-22

Practical 3.2 Using Object Oriented databases create the following types: 1. AddrType1 (Pincode: number, Street :char, City : char, state :char) 2. BranchType (address: AddrType1, phone1: integer,phone2: integer ) 3. AuthorType (name:char,,addr AddrType1) 4. PublisherType (name: char, addr: AddrType1, branches: BranchTableType 5. AuthorListType as varray, which is a reference to AuthorType Next create the following tables: 6. BranchTableType of BranchType 7. Authors of AuthorType 8. Books(title: varchar, year : date, a. published_by ref PublisherType,authors AuthorListType) 9. Publishers of PublisherType Insert 10 records into the above tables and fire the following queries: 1) List all of the authors that have the same pin code as their publisher: 2) List all books that have 2 or more authors: 3) List the name of the publisher that has the most branches 4) Name of authors who have not published a book 5) List all authors who have published more than one book: 6) Name of authors who have published books with at least two different publishers 7) List all books (title) where the same author appears more than once on the list of

authors (assuming that an integrity constraint requiring that the name of an author is unique in a list of authors has not been specified).

Page 145: DW & ADBMS-22

Creating Types : AddrType1 (Pincode: number, Street :char, City : char, state :char) Create or replace type addrtype1 as object ( pincode number(6), Street varchar2(15), City varchar2(15), State varchar2(15) ); BranchType (address: AddrType1, phone1: integer,phone2: integer ) Create or replace type branchtype as object ( address addrtype1, phone1 number(10), phone2 number(10)); AuthorType (name:char,,addr AddrType1) Create or replace type authortype as object ( name varchar2(10), addr addrtype1 ); PublisherType (name: char, addr: AddrType1, branches: BranchTableType Create or replace type publishertype as object ( name varchar(10), addr addrtype1, branches BranchTableType ); AuthorListType as varray, which is a reference to AuthorType Create or replace type AuthorListType as varray(5) of ref AuthorType; Creating Tables :

BranchTableType of BranchType Create or replace type BranchTableType as table of BranchType; Authors of AuthorType Create table Authors of AuthorType; Books(title: varchar, year : date, published_by ref PublisherType,authors AuthorListType) Create table Books (title varchar2(10), year date,published_by ref PublisherType, authors AuthorListType ); Publishers of PublisherType Create table Publishers of PublisherType Nested table branches store as Branchtab;

Page 146: DW & ADBMS-22

Inserting Records In Tables : Inserting records in authors table Insert into Authors Values ('Joe', addrtype1(1,'street1','pune','mh')); Insert into Aauthors Values ('Brad', addrtype1(2,'street2','mumbai','mh')); . . . Insert into authors values ('Rene', addrtype1(10,'street4','delhi','dl')); Inserting records in publishers table Insert into Publishers values ( 'lotus' , addrtype1( 1, 'ss street', 'mumbai', 'mh' ), branchtabletype(branchtype ( addrtype1 (1, 'ss street', 'mumbai', 'mh' ), 888888, 466666))); Insert into Publishers values ( 'venus' , addrtype1( 10, 'rs street', 'mumbai', 'mh' ), branchtabletype(branchtype ( addrtype1 (10, 'rs street', 'mumbai', 'mh' ), 898888, 466664))); Insert into Publishers values ( 'vegas' , addrtype10( 11, 'vega street', 'Dumbai', 'mh' ), branchtabletype10(branchtype10 ( addrtype10 (11, 'vega steet', 'Dumbai', 'mh' ), 898888, 466665))) Insert into Publishers values ( 'Segas’ , addrtype10( 12, 'sega street', 'Dubai', 'db' ), branchtabletype10(branchtype10 ( addrtype10 (12, 'sega steet', 'Dubai', 'db' ), 898777, 466666))) Insert into Publishers values ( 'Raga’ , addrtype10( 12, 'Raga street', 'Doha', 'dh' ), branchtabletype10(branchtype10 ( addrtype10 (12, 'Raga steet', 'Doha', 'dh' ), 898778, 466667))) Insert into Publishers values ( 'rose' , addrtype1( 20, 'CS Street', 'delhi', 'dl' ), branchtabletype(branchtype ( addrtype1 ( 20, 'CS Street', 'delhi', 'dl' ), 999909, 555710))); Inserting records in books table Insert into Books Select 'java','12-jan-2005', ref(pub), authorlisttype(ref(aut)) from publishers pub, authors aut where pub.name='lotus' and aut.name='joe'; Insert into Books Select 'oracle','12-mar-2005', ref(pub), authorlisttype(ref(aut)) from publishers pub, authors aut where pub.name='rose' and aut.name='brad'; Insert into Books Select 'j2me','12-may-2005', ref(pub), authorlisttype(ref(aut)) from publishers pub, authors aut where pub.name='lotus' and aut.name='Joe'; Insert into Books Select 'j2me','12-may-2005', ref(pub), authorlisttype(ref(aut)) from publishers pub, authors aut where pub.name='lotus' and aut.name='Joe'; Insert into Books Select 'v2me','12-oct-2005', ref(pub), authorlisttype10(ref(aut)) from publishers pub, authors aut where pub.name='vegas' and aut.name='Sue';

Page 147: DW & ADBMS-22

Insert into Books Select 's2me','12-nov-2005', ref(pub), authorlisttype10(ref(aut)) from publishers pub, authors aut where pub.name='Segas' and aut.name='Ullman'; Insert into Books Select 'j2me','12-nov-2005', ref(pub), authorlisttype10(ref(aut)) from publishers pub, authors aut where pub.name='vegas' and aut.name='Sue'; a) List all of the authors that have the same pin code as their publisher SQL> Select a.name,a.addr.pincode,p.addr.pincode from publishers p,authors a where p.addr.pincode=a.addr.pincode; NAME ADDR.PINCODE ADDR.PINCODE ------- ----------------- ----------------- Joe 1 1 Ullman 10 10 b) List all books that have 2 or more authors Sql> Select * from books b where 1 < ( select count(*) from table(b.authors)); Above Query will list all books that have 2 or more Authors. TITLE YEAR ---------- --------- PUBLISHED_BY -------------------------------------------------------------------------------- AUTHORS -------------------------------------------------------------------------------- 254FBFB57E20041126A0009) j2me 12-NOV-05 0000220208A83CD435F20945BCBB07628C7444D61A7589B06AD79D435289E34810DC4E441F AUTHORLISTTYPE10(00002802090040F59F58EA40A5B910AB97952A11CB7A00B537542B46D79EAF7 254FBFB57E20041126A0009) TITLE YEAR ---------- --------- PUBLISHED_BY -------------------------------------------------------------------------------- AUTHORS -------------------------------------------------------------------------------- j2me 12-NOV-05 0000220208A83CD435F20945BCBB07628C7444D61A7589B06AD79D435289E34810DC4E441F AUTHORLISTTYPE10(0000280209C90272A3DC644A2FB36D88D433F976F97A00B537542B46D79EAF7 254FBFB57E20041126A0006)

Page 148: DW & ADBMS-22

c) List the name of the publisher that has the most branches Sql> Select p.name from publishers p, table(p.branches) group by p.name having count(*)> = all (select count(*) from publishers p, table(p.branches) group by name); Above Query will list name of the publishers that have most branches. NAME ---------- rose d) Name of authors who have not published a book: Sql> Select a.name from authors10 a where not exists (Select b.title from books10 b, Table(select authors from books10 b1 Where b.title = b1.title) Where a.name = name); Output : no rows selected.

Page 149: DW & ADBMS-22

Roll No. – 22

NAAC Accreditation “A” Grade Deccan Education Society’s

Kirti M. Doongursee College, Dadar, Mumbai-28 Dept. of Computer Science & I.T.

M.Sc. (Part-I) 2006 – 07 Subject: ADBMS

Practical No:4 ACTIVE DATABASES

Create a table emp (eno, ename, hrs, pno, super_no) and project (pname, pno, thrs, head_no) where thrs is the total hours and is the derived attribute. Its value is the sum of hrs of all employees working on that project. eno and pno are primary keys, head_no is foreign key to emp relation. Insert 10 tuples and write triggers to do the following:

a) Creating a trigger to insert a new employee tuple and display the new total hours from project table.

b) Creating a trigger to change the hrs of existing employee and display the new total hours from project table.

c) Creating a trigger to change the project of an employee and display the new total hours from project table.

d) Creating a trigger to deleting the project of an employee.

Page 150: DW & ADBMS-22

OUTPUT: Query To Create Table Emp Create table Emp(eno number(10) primary key, ename varchar2(20), hrs number(10), pno number(10), super_no number(10)); Query to create table project Create table project(pname varchar2(20), pno number(10) primary key, thrs number(21), head_no number(10)); Inserting values Into Emp table: Insert into emp values(1,'John',8,1,1) Insert into emp values(2,'Smith',2,1,2) Insert into emp values(3,'Joe',5,3,3) Insert into emp values(4,'Julie',6,3,4) Sql> Select * from Emp

ENO ENAME HRS PNO SUPER_NO 1 John 8 1 1 2 Smith 2 1 2 3 Joe 5 3 3 4 Julie 6 3 4

Inserting values Into Project table: insert into project values('inventory',1,10,1) insert into project values('crm',2, 0, 2) insert into project values('vb',3,11,3) Sql> Select * from Project;

PNAME PNO THRS HEAD_NO

inventory 1 10 1

Crm 2 0 2

Vb 3 11 3 Questions: a) Creating a trigger to insert a new employee tuple and display the new total hours from

project table. Sql> CREATE OR REPLACE TRIGGER thrs1 AFTER INSERT ON EMP FOR EACH ROW BEGIN UPDATE PROJECT SET thrs= thrs + :new.hrs where pno=:new.pno; END;

Page 151: DW & ADBMS-22

Output : Trigger Created. Inserting a New Record into EMP table. Insert into empt values(5,'Robin',2,2,5); Description: After inserting the new record the trigger thrs1 will be executed and the thrs in the project table will be updated. i.e , in this case thrs was equal to 0 before inserting above record. now thrs will be old.thrs + new.thrs ie(0+2=2) where pno=2; Before Insertion:

Pname Pno thrs Head_no

Crm 2 0 2

After Insertion:

Pname Pno thrs Head_no

Crm 2 2 2

b) Creating a trigger to change the hrs of existing employee and display the new total hours

from project table. Sql> CREATE OR REPLACE TRIGGER thrs2 AFTER UPDATE OF hrs ON EMP FOR EACH ROW BEGIN UPDATE PROJECT SET thrs= thrs + (:NEW.hrs) - (:OLD.hrs) Where pno=:NEW.pno; END; Output : Trigger Created. Updating a Record from Emp table Sql> update emp set hrs=3 where eno=2; Description: After updating the record of eno=2 the trigger thrs1 will be executed and the thrs in the project table will be updated. i.e, In this case thrs was equal to 10 before inserting above record. now thrs will be old.thrs + new.thrs – old.thrs ie(10+3-2=11) where pno=1.

Page 152: DW & ADBMS-22

Before Insertion:

Pname Pno thrs Head_no

Crm 1 10 1 After Insertion:

Pname Pno thrs Head_no

Crm 1 11 1 c) Creating a trigger to change the project of an employee and display the new total hours

from project table. Sql> CREATE or replace TRIGGER thrs3 AFTER UPDATE OF PNO ON EMP FOR EACH ROW BEGIN Update project SET thrs= thrs - :old.hrs WHERE pno=:old.PNO; Update Project SET thrs= thrs + :NEW.hrs WHERE pno=:NEW.PNO; END; Output : Trigger Created. Updating a Record from Emp table Sql> update emp set pno=2 where ename='Julie'; Description: After updating the record of pno=2 to 3 ,the trigger thrs3 will be executed and the thrs in the project table will be updated.

i.e, In this case thrs of pno=2 was 2 and of pno=3 was 11 before inserting above record. Now thrs will be thrs=thrs - :old.hrs (11-6=5) where pno=3

and thrs=thrs + :new.hrs (6+2=8) where pno=2.

Before Insertion:

PNAME PNO THRS HEAD_NO Crm 2 2 2 Vb 3 11 3

After Insertion:

PNAME PNO THRS HEAD_NO crm 2 8 2 vb 3 5 3

Page 153: DW & ADBMS-22

d) Creating a trigger to deleting the project of an employee. Sql> CREATE or replace TRIGGER thrs4 Before DELETE ON EMP FOR EACH ROW BEGIN update project Set thrs = thrs - (:OLD.hrs) WHERE pno= (:OLD.pno); END; Output: Trigger Created. Deleting a Record from Emp table. Sql> delete from empt where eno=1; Description: After deleting the record of eno=1 from emp ,the trigger thrs4 will be executed and the thrs in the project table will be updated. i.e, In this case thrs of pno=1 was 11 before deleting above record. Now thrs = thrs - :old.hrs (11-8=3) where pno=1. Before Insertion:

PNAME PNO THRS HEAD_NO Inventory 1 11 1

After Insertion:

PNAME PNO THRS HEAD_NO Inventory 1 3 1

Page 154: DW & ADBMS-22

Roll No. – 22

NAAC Accreditation “A” Grade Deccan Education Society’s

Kirti M. Doongursee College, Dadar, Mumbai-28 Dept. of Computer Science & I.T.

M.Sc. (Part-I) 2006 – 07 Subject: ADBMS

Practical 05

TEMPORAL DATABASES

5.1 Create a table tblEmp_Appnt, which stores the account number, name, and valid time

say, recruitment date and retirement date. Insert 10 records and fire the following queries

a) Find all the employees who join the company on 2/3/2001 b) Find all the employees who will retired on 2/3/2001

Page 155: DW & ADBMS-22

OUTPUT 5.1: Query for creating table tblEmp_Appnt Create table tblEmp_Appnt ( ACC NO NUMBER(10), NAME VARCHAR2(10), RECDATE DATE, RETDATE DATE ); Inserting Records In Table tblEmp_Appnt Insert into tblemp_Appnt values(10,'JOHN','01-JAN-85’,'01-JAN-93'); Insert into tblemp_Appnt values(20,'PAUL','21-FEB-85’,'01-JAN-95'); Insert into tblemp_Appnt values(30,'GEORGE',’02-SEP-91’,); . . Insert into tblemp_Appnt values(60,'RETIRED',’01-JAN-79’,’02-MAR-01’); Sql> SELECT * FROM tblEmp_Appnt;

ACCNO NAME RECDATE RETDATE

10 JOHN 1-Jan-85 1-Jan-93

20 PAUL 21-Feb-88 1-Apr-95

30 GEORGE 2-Sep-91

40 REENA 15-Oct-89 20-Dec-05

50 SUE 2-Mar-01

60 RETIRED 1-Jan-79 2-Mar-01 a) Find all the employees who join the company on 2/3/2001 Sql> SELECT * FROM tblEmp_Appnt WHERE RECDATE='02-MAR-2001';

ACCNO NAME RECDATE RETDATE 50 SUE 2-Mar-01

b) Find all the employees who will retired on 2/3/2001 Sql> SELECT * FROM tblEmp_Appnt WHERE RETDATE='02-MAR-2001';

ACCNO NAME RECDATE RETDATE 60 RETIRED 1-Jan-79 2-Mar-01

Page 156: DW & ADBMS-22

Practical 5.2 TEMPORAL DATABASES

5.2 Create a table tbl_shares, which stores the, name of company, number of shares, and price per share at transaction time. Insert 10 records and fire the following queries.

a) Find all the names of a company whose share price is more than Rs. 100 at 11:45 A.M.

b) Find the name of company which has highest share price at 5.00 P.M.

Page 157: DW & ADBMS-22

OUTPUT 5.2: Query for creating table tbl_shares Create table:-

SQL> create table tbl_shares 2 ( 3 cmp_name varchar2(20), 4 no_of_shares number(3), 5 price number(4,2), 6 tdate date 7 ); Table created. Trigger tig5share.sql:-

SQL>create or replace trigger TrigShares before insert or update on tbl_shares referencing NEW as new for each row

declare stDate varchar2(30); endDate varchar2(30); begin select to_char(least(sysdate, to_date('10:30:00 am','hh:mi:ss am'), to_date('03:30:00 pm','hh:mi:ss pm')), 'hh:mi:ss am') into stDate from dual;

select to_char(greatest(sysdate, to_date('10:30:00 am','hh:mi:ss am'), to_date('03:30:00 pm','hh:mi:ss pm')), 'hh:mi:ss am') into endDate from dual;

if ( stDate='10:30:00 am' and endDate='03:30:00 pm' )then

dbms_output.put_line('Valid time'); :new.tdate:=sysdate;

else RAISE_APPLICATION_ERROR(-20001,'Invalid Time');

end if; end;

Page 158: DW & ADBMS-22

Trigger:- SQL> @tig5share.sql; Trigger created. Queries:- SQL> select compname from tbl_shares1 where to_char(share_time,'hh:mi:ss am')='11:45:00 am' and sha re_price>100; COMPNAME -------------------- Oracle Dbms SQL> select compname from tbl_shares1 where share_price=(select max(share_price) from tbl_shares1 wh ere to_char(share_time,'hh:mi:ss pm')='05:00:00 pm'); COMPNAME -------------------- wipro Inserting Records In Table tbl_shares Insert into tbl_shares values('MAERSK',200,80, DEFAULT); Insert into tbl_shares values('ESERVE',100,120,DEFAULT); Insert into tbl_shares values('CMS',200,100,DEFAULT); Insert into tbl_shares values('CMC',200,25, DEFAULT); Insert into tbl_shares values('JP MORGAN',200,50, DEFAULT); Sql> SELECT * FROM tbl_shares;

COMPNAME NOSHARE PRICE TRANSTIME MAERSK 200 80 12:35 ESERVE 100 120 12:36

CMS 100 150 11:45 CMC 25 200 11:45

COGNIZANT 125 175 17:00 WIPRO 300 500 17:00

RELIANCE 400 1000 17:00 JP MORGAN 50 175 11:45

Page 159: DW & ADBMS-22

a) Find all the names of a company whose share price is more than Rs. 100 at 11:45 A.M. SQL> Select compname,transtime from tbl_shares where price > 100 and transtime='11:45';

COMPNAME PRICE TRANSTIME CMS 150 11:45 CMC 200 11:45

JP MORGAN 175 11:45 b) Find the name of company which has highest share price at 5.00 P.M. SQL> Select * from tbl_shares where price = (select max(price) from tbl_shares where transtime=’17:00’);

COMPNAME NOSHARE PRICE TRANSTIME RELIANCE 400 1000 17:00

Page 160: DW & ADBMS-22

Roll No. – 22

NAAC Accreditation “A” Grade Deccan Education Society’s

Kirti M. Doongursee College, Dadar, Mumbai-28 Dept. of Computer Science & I.T.

M.Sc. (Part-I) 2006 – 07 Subject: ADBMS

Practical No:6

SPATIAL DATABASE Create a spatial database table that stores the number, name and location, which consists of four different areas say cola_a, cola_b, cola_c and cola_d. Fire the following queries

a) Find the topological intersection of two geometries. b) Find whether two geometric figures are equivalent to each other. c) Find the areas of all different locations. d) Find the area of only one location. e) Find the distance between two geometries.

Page 161: DW & ADBMS-22

OUTPUT: Steps:

Creates a table (COLA_MARKETS) to hold the spatial data Inserts rows for four areas of interest (cola_a, cola_b, cola_c, cola_d) and Updates the USER_SDO_GEOM_METADATA view to reflect the dimensional

information for the areas Creates a spatial index (COLA_SPATIAL_IDX) Performs some spatial queries

To check the version:

SELECT SDO_VERSION FROM DUAL;

Error Messages:

Spatial error message numbers are in the range of 13000 to 13499. CREATE TABLE cola_markets ( mkt_id NUMBER PRIMARY KEY, name VARCHAR2(32), shape MDSYS.SDO_GEOMETRY) / The above query creates a table cola_markets. Structure of SDO_GEOMETRY: CREATE TYPE sdo_geometry AS OBJECT ( SDO_GTYPE NUMBER, SDO_SRID NUMBER, SDO_POINT SDO_POINT_TYPE, SDO_ELEM_INFO MDSYS.SDO_ELEM_INFO_ARRAY, SDO_ORDINATES MDSYS.SDO_ORDINATE_ARRAY); Queries for inserting the cola_a, cola_b, cola_c, cola_d shapes in the table.

INSERT INTO cola_markets VALUES ( 1, 'cola_a', MDSYS.SDO_GEOMETRY( 2003, NULL, NULL, MDSYS.SDO_ELEM_INFO_ARRAY ( 1, 1003, 3 ), MDSYS.SDO_ORDINATE_ARRAY (1,1,5,7) ) )

Page 162: DW & ADBMS-22

Explanation of above query:

SDO_GTYPE = 2003. The 2 indicates two-dimensional, and the 3 indicates a polygon. SDO_SRID = NULL. SDO_POINT = NULL. SDO_ELEM_INFO = (1, 1003, 3). 1 -- Indicates the offset within the SDO_ORDINATES array where the first

ordinate for this element is stored. 1003 -- SDO_ETYPE - Indicates the type of the element. 3 -- indicates that this is a rectangle. SDO_ORDINATES = (1,1,5,7). These identify the lower-left and upper-right ordinates of

the rectangle.

INSERT INTO cola_markets VALUES( 2, 'cola_b', MDSYS.SDO_GEOMETRY( 2003, -- 2-dimensional polygon NULL, NULL, MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,1), -- One polygon (exterior polygon ring) MDSYS.SDO_ORDINATE_ARRAY(5,1, 8,1, 8,6, 5,7, 5,1) ) ); INSERT INTO cola_markets VALUES( 3, 'cola_c', MDSYS.SDO_GEOMETRY( 2003, -- 2-dimensional polygon NULL, NULL, MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,1), -- one polygon (exterior polygon ring) MDSYS.SDO_ORDINATE_ARRAY(3,3, 6,3, 6,5, 4,5, 3,3) ) );

INSERT INTO cola_markets VALUES( 4, ’cola_d’, MDSYS.SDO_GEOMETRY( 2003, -- 2-dimensional polygon NULL, NULL, MDSYS.SDO_ELEM_INFO_ARRAY(1,1003,4), -- one circle MDSYS.SDO_ORDINATE_ARRAY(8,7, 10,9, 8,11) ) );

Page 163: DW & ADBMS-22

Query for inserting Metadata

INSERT INTO USER_SDO_GEOM_METADATA VALUES ( ’cola_markets’, -- table name ’shape’, -- column name MDSYS.SDO_DIM_ARRAY( MDSYS.SDO_DIM_ELEMENT( ’X’, 0, 20, 0.005 ), MDSYS.SDO_DIM_ELEMENT(’Y’, 0, 20, 0.005) ), NULL -- SRID coordinate system );

Query for creating Index so as to access the data faster.

CREATE INDEX cola_spatial_idx ON cola_markets(shape) INDEXTYPE IS MDSYS.SPATIAL_INDEX;

1) Return the topological intersection of two geometries.

SELECT SDO_GEOM.SDO_INTERSECTION -- Returns a geometry object that is the --topological intersection (AND operation) of two geometry objects.

(c_a.shape, --geom1 c_c.shape, --geom2 0.005 -- tolerance ) FROM cola_markets c_a, cola_markets c_c WHERE c_a.name = 'cola_a' AND c_c.name = 'cola_c'; Output:- SDO_GEOM.SDO_INTERSECTION(C_A.SHAPE,C_C.SHAPE,0.005)(SDO_GTY PE, SDO_SRID, SDO_PO -------------------------------------------------------------------------------- SDO_GEOMETRY(2003, NULL, NULL, SDO_ELEM_INFO_ARRAY(1, 1003, 1), SDO_ORDINATE_ARRAY(4, 5, 3, 3, 5, 3, 5, 5, 4, 5))

2) Find whether two geometric figures are equivalent to each other. SELECT SDO_GEOM.RELATE(c_c.map, 'EQUAL', c_a.map, 0.005) FROM cola_markets c_c, cola_ markets c_a WHERE c_c.name = 'cola_c' AND c_a.name = 'cola_a'; Output:- SDO_GEOM.RELATE(C_C.MAP,'EQUAL',C_A.MAP,0.005) -------------------------------------------------------- FALSE The following mask relationship can be tested:

Page 164: DW & ADBMS-22

• EQUAL: Returns EQUAL if the objects share every point of their boundaries and interior, including any holes in the objects; otherwise, returns FALSE.

3) Return the areas of all cola markets. SELECT name, SDO_GEOM.SDO_AREA(shape, 0.005) FROM cola_markets; Output:- NAME SDO_GEOM.SDO_AREA(SHAPE,0.005) ------------------------------ ---------------------------- cola_a 24 cola_b 16.5 cola_c 5 cola_d 12.5663706

4) Find the area of only one location.

SELECT c.name, SDO_GEOM.SDO_AREA(c.shape, 0.005) FROM cola_markets c WHERE c.name = 'cola_a';

Output:- NAME SDO_GEOM.SDO_AREA(C.SHAPE,0.005) -------------------------------- -------------------------------- cola_a 24

5) Return the distance between two geometries.

SELECT SDO_GEOM.SDO_DISTANCE -- Computes the distance between two geometry objects. (c_b.shape, -- geom1 c_d.shape, -- geom.2 0.005 -- tolerance ) FROM cola_markets c_b, cola_markets c_d WHERE c_b.name = 'cola_b' AND c_d.name = 'cola_d';

Output:-

SDO_GEOM.SDO_DISTANCE(C_B.SHAPE,C_D.SHAPE,0.005) ------------------------------------------------ .846049894

Page 165: DW & ADBMS-22

Roll No. – 22

NAAC Accreditation “A” Grade Deccan Education Society’s

Kirti M. Doongursee College, Dadar, Mumbai-28 Dept. of Computer Science & I.T.

M.Sc. (Part-I) 2006 – 07 Subject: ADBMS

Practical No:7

Concept of XML Database Create a table DemoEmp having emp_id as number datatype and employee_spec as XML datatype (XMLType).The employee_spec is a schema with attributes emp id, name, email, acc_no, managerEmail, dateOf Joning. Insert 10 tuples into employee table. Fire the following queries on XML database. a) Retrieve the names of employee. b) Retrieve the acc_no of employees. c) Retrieve the names,acc_no, email of employees. d) Update the 3rd record from the table and display the name of an employee. e) Delete 4 th record from the table.

Page 166: DW & ADBMS-22

OUTPUT: Queries: Create Table Demoemp (Emp_Id Number(5),Emp_specification XMLTYPE);

Fields Data Type EMP_ID Number(5)

Employee_Spec XMLTYPE

Now insert 3 values in above table

1. Insert Into Demoemp Values(1,XMLTYPE( '<emp> <empid>1</empid> <name>Aditi</name> <email>[email protected]</email> <accountno> 01</accountno> <dob>05/09/1984</dob> </emp>' ) ); 2. Insert Into Demoemp Values(2,XMLTYPE('<emp> <empid>2</empid> <name>Punita</name> <email>[email protected]</email> <accountno>11</accountno> <dob>08/02/1985</dob> </emp>' ) ); 3. Insert Into Demoemp Values(3,XMLTYPE('<emp> <empid>3</empid> <name>shreyas</name> <email>[email protected]</email> <accountno>10</accountno> <dob>02/02/1985</dob> </emp>' ) );

Page 167: DW & ADBMS-22

a) Retrieve the names of employee. SELECT e.emp_specification.EXTRACT('/emp/name/text()').getstringval() Names of Employee" FROM demoemp e; Output: Names of employee -------------------------------------------------------------------------------- Aditi Punita Shreyas Shreyas

b) Retrieve the acc_no of employees.

SELECT e.emp_specification.EXTRACT('/emp/accountno/text()').getStringVal() "Account Number" From DemoEmp e; Output :- Account Number -------------------------------------------------------------------------------- 11

c) Retrieve the names, acc_no, email of employees.

SELECT e.emp_specification.EXTRACT('emp/name/text()').getStringVal() "Emp Name", e.emp_specification.EXTRACT('/emp/email/text()').getStringVal() "Email Id", e.emp_specification.EXTRACT('/emp/accountno/text()').getStringVal() "Account No" FROM DemoEmp e; Output :- Emp Name -------------------------------------------------------------------------------- Email Id -------------------------------------------------------------------------------- Account No -------------------------------------------------------------------------------- Aditi [email protected] 10 Punita [email protected] 12

Page 168: DW & ADBMS-22

Emp Name -------------------------------------------------------------------------------- Email Id -------------------------------------------------------------------------------- Account No -------------------------------------------------------------------------------- shreyas [email protected] 11

d) Update the 3rd record from the table and display the name of an employee UPDATE DemoEmp e SET emp_specification = XMLType

('<emp> <empid>1</empid>

<name>suyog</name> <email>[email protected]</email> <dob>05/09/1984</dob> </emp>') where emp_id=2);

Select e.emp_specification.EXTRACT('/emp/name/text()').getStringVal() "Employee name" from demoemp e where emp_id=2

Output :-

Employee name -------------------------------------------------------------------------------- Suyog

e) Delete 4 th record from the table.

DELETE from demoemp e where e.emp_specification.EXTRACT('emp/name/text()').getStringVal()='Aditi';

Output :- 1 row deleted.

Page 169: DW & ADBMS-22

Roll No. – 22

NAAC Accreditation “A” Grade Deccan Education Society’s

Kirti M. Doongursee College, Dadar, Mumbai-28 Dept. of Computer Science & I.T.

M.Sc. (Part-I) 2006– 07 Subject: ADBMS

Practical No.8

Multimedia Databases 8.1 Create a table Empimg with the attributes Eno as employee number, Ename as employee name, Eaddress as employee address and photo as an employee picture. Also create a table Company with attributes Eno,designation,age. Fire the following queries

i. Find name and designation of all the employees ii. Find name and age of all the employees iii. Find name and photo of a particular employee

Page 170: DW & ADBMS-22

Practical No:8.1 Concept of multimedia database Insert an image in the table EMPIMG, the table consist of following attributes Using Java Program,Insert and Display the Image back.

SQL Queries for creating tables Empimg and Company: -

Create table Empimg ( Eno Number(5), Ename varchar2(25), Eaddress varchar2(25), Photo BLOB ); Create table Company ( Eno Number(5), Designation varchar2(15), Age Number(5) );

Column Name Data Type Eno Number

Ename Varchar2(25) Eaddress Varchar2(25)

Photo BLOB

Column Name Data Type Eno Number(5)

Designation Varchar2(15) Age Number(5)

Page 171: DW & ADBMS-22

Java Program to Insert images in EMPIMG Table import java.sql.*; import java.io.*; public class InsertImage { public InsertImage() { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection c = DriverManager.getConnection ("jdbc:odbc:dsn26","scott","tiger");

Statement s=c.createStatement(); int i = 1;

String names[] = {"Joe","Steve","John","Justin","Thomas","Richard","Jake","Timothy","Sam","Kent","Tobias"}; String city[] = {"Mumbai","Kolkatta","Chennai","Panji","Hyderabad","Banglore","Manglore","OOty","Simla","Shrinagar","Kerala"};

File file; FileInputStream fis; PreparedStatement psmt; for(i=1;i<=10;i++) { file = new File(i+".gif"); fis = new FileInputStream(file); psmt=c.prepareStatement("Insert into empimg values(?,?,?,?)"); psmt.setInt(1,i); psmt.setString(2,names[i]); psmt.setString(3,city[i]); psmt.setBinaryStream(4,fis,(int)file.length()); psmt.executeUpdate(); } } catch(Exception e) { System.out.println("Error: "+e); } }

public static void main(String[] args) { new InsertImage(); System.out.println("Image Inserted Successfully"); } }

Page 172: DW & ADBMS-22

i) Java Program for Displaying the Name & Designation of all Employees

import javax.swing.*; import java.awt.*; import java.awt.event.*; import javax.swing.event.*; import java.sql.*; public class AgeNDesg extends JFrame { JTextField txtname=new JTextField(10); JTextField txtage=new JTextField(10); JTextField txtdes=new JTextField(10); ResultSet rs; ResultSetMetaData rsmd; int colcount=0,col=0; public AgeNDesg() { JLabel label=new JLabel("View Accounts Details.............."); JLabel lname=new JLabel("Name :"); JLabel ltype=new JLabel("Age :"); JLabel lbal=new JLabel("Desgination :"); JButton first=new JButton("First"); JButton pre=new JButton("Previous"); JButton next=new JButton("Next"); JButton last=new JButton("Last"); JPanel input=new JPanel(); JPanel lpanel=new JPanel(); JPanel button=new JPanel();

Page 173: DW & ADBMS-22

first.setMnemonic('F'); pre.setMnemonic('P'); next.setMnemonic('N'); last.setMnemonic('L'); lpanel.setLayout(new FlowLayout(FlowLayout.LEFT)); lpanel.add(label); lpanel.setBorder(BorderFactory.createTitledBorder("")); getContentPane().add(lpanel,BorderLayout.NORTH); input.add(lname); input.add(txtname); input.add(ltype); input.add(txtage); input.add(lbal); input.add(txtdes); input.setLayout(new GridLayout(3,2,6,6) ); input.setBorder(BorderFactory.createTitledBorder(" Details ")); getContentPane().add(input,BorderLayout.CENTER); button.add(first); button.add(pre); button.add(next); button.add(last); button.setLayout(new GridLayout(2,2,5,5)); button.setBorder(BorderFactory.createTitledBorder(" Navigation ")); getContentPane().add(button,BorderLayout.SOUTH); txtname.setEnabled(true); txtage.setEnabled(true); txtdes.setEnabled(true); setTitle("Employee Details"); setSize(320,250); setVisible(true); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { setVisible(false); dispose(); new Emp(); } }); try {

Page 174: DW & ADBMS-22

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection conn = DriverManager.getConnection("jdbc:odbc:dsn26","scott","tiger"); Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet

.CONCUR_READ_ONLY); rs=stmt.executeQuery("Select e.Ename,c.Age,c.Designation from

Empimg e,Company c where e.eno=c.eno"); rsmd=rs.getMetaData(); colcount=rsmd.getColumnCount()-1; while(rs.next()) System.out.println(rs.getString(1)+","+rs.getString(2)+","+rs.getString(3)); } catch(Exception e) { System.out.println("ERROR....... "+e); e.printStackTrace(); } first.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { try { rs.first(); System.out.println("First Record.."); colcount=1; txtname.setText(rs.getString(1)); txtage.setText(rs.getString(2)); txtdes.setText(rs.getString(3)); System.out.println(colcount); } catch(Exception e) { e.printStackTrace(); } } }); pre.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { try { if(!rs.isFirst()) {

Page 175: DW & ADBMS-22

rs.previous(); System.out.println("Previous Record..."); } else { rs.first(); System.out.println("First Record..."); } txtname.setText(rs.getString(1)); txtage.setText(rs.getString(2)); txtdes.setText(rs.getString(3)); System.out.println(colcount); }

catch(Exception e) { e.printStackTrace(); } } }); next.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { try { if(!rs.isLast()) { rs.next(); System.out.println("Next Record..."); } else { rs.last(); System.out.println("Last Record..."); } txtname.setText(rs.getString(1)); txtage.setText(rs.getString(2)); txtdes.setText(rs.getString(3)); System.out.println(colcount); } catch(Exception e) { e.printStackTrace(); } } });

Page 176: DW & ADBMS-22

last.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { try { rs.last(); colcount=rsmd.getColumnCount()-1; txtname.setText(rs.getString(1)); txtage.setText(rs.getString(2)); txtdes.setText(rs.getString(3)); System.out.println(colcount); } catch(Exception e) { e.printStackTrace(); } } }); }

public static void main(String[] args) { new AgeNDesg(); System.out.println("Hello World!"); } }

Page 177: DW & ADBMS-22

ii) Display Name and Age of all the Employees(Program code as illustrated above).

Page 178: DW & ADBMS-22

iii) Java Program to Display Name and Photo of a particular Employee.

import javax.swing.*; import java.awt.*; import java.awt.event.*; import javax.swing.event.*; public class Emp extends JFrame { public Emp() { JLabel ltitle=new JLabel("Employee Details"); JLabel label=new JLabel("Select Desired Option................"); JButton view=new JButton("View All"); JButton ad=new JButton("Age & Designation"); JButton show=new JButton("Snap"); JButton ok=new JButton("EXIT"); JPanel panel=new JPanel(); JPanel title=new JPanel(); JPanel lpanel=new JPanel(); view.setMnemonic('V'); ad.setMnemonic('A'); show.setMnemonic('S'); ok.setMnemonic('E'); title.setLayout(new FlowLayout(FlowLayout.CENTER)); title.add(ltitle); getContentPane().add(title,BorderLayout.NORTH); lpanel.setLayout(new FlowLayout(FlowLayout.LEFT)); lpanel.add(label);

Page 179: DW & ADBMS-22

lpanel.setBorder(BorderFactory.createTitledBorder("")); getContentPane().add(lpanel,BorderLayout.CENTER); panel.add(view); panel.add(ad); panel.add(show); panel.add(ok); panel.setLayout(new GridLayout(2,2,6,5)); panel.setBorder(BorderFactory.createTitledBorder(" Options ")); getContentPane().add(panel,BorderLayout.SOUTH); setTitle("Employee Details..."); setSize(320,190); setVisible(true); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { setVisible(false); dispose(); System.exit(0); } }); view.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { System.out.println("View"); setVisible(false); new Viewall(); } }); ad.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { System.out.println("Deposit"); setVisible(false); new AgeNDesg(); } }); show.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) {

Page 180: DW & ADBMS-22

System.out.println("Deposit"); setVisible(false); new DisplayImage(); } }); ok.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { System.out.println("OK"); System.exit(0); } }); } public static void main(String[] args) { System.out.println("Hello World!"); new Emp(); } }

Page 181: DW & ADBMS-22

Practical No:8.2 Concept of multimedia database 8.2 Create a table Singer1 with the attributes sno as singer number, Sname as singer name, Saddress as singer address and audio as an audio clip. Also create a table Company1 with attributes Sno,age. Fire the following queries

i) Find name and age of all the singer ii) Find name and audio clip of a particular singer

Insert an Audio file in the table Singer1. The table consists of following Column

Query to create Table Singer1 :

Create Table Singer1 ( Sno Number(3), Sname Varchar2(10), Saddress Varchar2(25), Audio BLOB ); Create Table Company1 ( Sno Number(5) Age Number(5) );

Field Name Data Type Sno Number(5)

Sname Varchar2(15) Saddress Varchar2(25)

Audio BLOB

Field Name Data Type Sno Number(5) Age Number(5)

Page 182: DW & ADBMS-22

Java Program for Insertion of Audio File in to Table Singer1

import java.io.*; import java.sql.*; import javax.swing.*; import java.awt.*; import javax.swing.event.*; import java.awt.event.*; public class AddAudio { public static void main(String[] args) { new AddAudio(); } AddAudio() { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String names[] = {"Joe","Steve","John","Justin","Thomas","Richard","Jake","Timothy","Sam","Kent","David"}; String city[] = {"Mumbai","Kolkatta","Chennai","Panji","Hyderabad","Banglore", "Manglore","Ooty","Simla","ShriNagar","Nasik"}; Connection c = DriverManager.getConnection("jdbc:odbc:DSN26","scott","tiger"); Statement s = c.createStatement(); int i=1; File file; FileInputStream fis; PreparedStatement psmt; for(i=1;i<=10;i++) { file = new File(i+".wav"); fis = new FileInputStream(file); psmt=c.prepareStatement("Insert into Singer1 values(?,?,?,?)"); psmt.setInt(1,i); psmt.setString(2,names[i]); psmt.setString(3,city[i]); psmt.setBinaryStream(4,fis,(int)file.length()); psmt.executeUpdate(); } System.out.println("Audio Files Inserted Successfully"); } catch (Exception e) { e.printStackTrace(); } } }

Page 183: DW & ADBMS-22

i) Find Name and Age of all the Singers.

SQL> Select s1.Sname,s2.Age from Singer1 s1,Company1 s2 where s1.sno=s2.sno;

SNAME AGE Steve 35 John 20 Justin 25

Thomas 45 Richard 30

Jake 28 Timothy 20

Sam 25 Kent 40 David 50

ii) Find Name and Audio Clip of a particular Singer

Java Program for Retrieving and Playing the Audio file inserted in to table Singer1:-

import java.io.*; import java.sql.*; import javax.swing.*; import javax.media.*; import java.awt.*; import java.awt.event.*; import java.net.*; import java.io.*; public class PlayAudio extends JFrame { Player player; JTextField txtno=new JTextField(); JTextField txtname=new JTextField(); JLabel lno=new JLabel("SNo. : "); JLabel lname=new JLabel("Name : "); JPanel no=new JPanel(); JPanel name=new JPanel(); JPanel both=new JPanel(); JButton ok=new JButton("OK"); Component center; Component south; Connection c; byte[] bytes; ResultSet rs; ResultSetMetaData rsmd; Statement stmt; String fileName;

Page 184: DW & ADBMS-22

String path; File outFile; FileOutputStream outStream; File file; URL url; Container contentPane; Component cpc; public PlayAudio() { contentPane=getContentPane(); no.setBorder(BorderFactory.createTitledBorder(" Enter No ")); no.setLayout(new GridLayout(1,3,5,5)); no.add(lno); no.add(txtno); no.add(ok); name.setBorder(BorderFactory.createTitledBorder("")); name.setLayout(new GridLayout(1,2,5,5)); name.add(lname); name.add(txtname); txtname.setEnabled(false); both.setBorder(BorderFactory.createTitledBorder("")); both.setLayout(new BorderLayout()); both.add(no,BorderLayout.NORTH); both.add(name,BorderLayout.CENTER); contentPane.add(both,BorderLayout.NORTH); setTitle("Play Audio"); setSize(200,200); setVisible(true); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { if(player!=null) { player.stop(); } setVisible(false); freeAll(); dispose(); System.exit(0); } }); try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection conn = DriverManager.getConnection ("jdbc:odbc:DSN26","scott","tiger"); stmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);

Page 185: DW & ADBMS-22

} catch(Exception e) { e.printStackTrace(); } ok.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { try { if(player!=null) { player.stop(); } System.out.println("The Value Entered Is: ++"+txtno.getText()+"++"); Integer no=0; try { no=Integer.parseInt(txtno.getText()); } catch(NumberFormatException nfe) { txtname.setText("Invalid Number!!"); txtno.setText(""); } if(!txtno.getText().equals("")) { System.out.println("Inside..."); rs=stmt.executeQuery ("Select sname,audio from singer where sno="+no); rsmd=rs.getMetaData(); rs.first(); try{ txtname.setText(rs.getString("sname")); if(player!=null) { player.stop(); player=null; } contentPane=null; putFile(); txtname.setText(""); } catch(SQLException s) { System.out.println("OOOOHHHH");

Page 186: DW & ADBMS-22

txtname.setText("No Data For This Eno."); txtno.setText(""); } try { txtname.setText(rs.getString("sname")); } catch(SQLException e) { txtname.setText("No Data For This Eno."); } } else { txtname.setText("No Data For This Eno."); } } catch(Exception e) { e.printStackTrace(); } } }); } //constructor close void putFile() { try{ bytes=new byte[100]; bytes=rs.getBytes("audio"); fileName = new String ( "Retrivedaudio.wav"); path = new String ( "C:\\WINNT\\Temp" ); outFile = new File ( path, fileName ); outStream = new FileOutputStream ( outFile ); System.out.println ( "Writing to file: " + outFile.getName() ); for ( int i = 0; i < bytes.length; i++ ) { try { outStream.write ( bytes [ i ] ); } catch ( IOException e ) { System.out.println("Error: " +e ); } } System.out.println("length:" +bytes.length); outStream.close (); File f =new File("C:/WINNT/Temp/Retrivedaudio.wav");

Page 187: DW & ADBMS-22

load(f); }catch(Exception ae) { System.out.println("ERROR!!! : ........ "+ae); } } public void freeAll() { player=null;txtno=null;txtname=null;lno=null; lname=null;no=null;name=null;both=null; ok=null;center=null;south=null;c=null;bytes=null;rs=null;rsmd=null;stmt=null;fileName=null; path=null;outFile=null;outStream=null;file=null;url=null;contentPane=null;cpc=null; } public void load(final File file) { try{ url=file.toURL(); contentPane=getContentPane(); if (player != null) { player.stop(); } player = Manager.createPlayer(url); ControllerListener listener = new ControllerAdapter() { public void realizeComplete(RealizeCompleteEvent event) { cpc = player.getControlPanelComponent(); if (cpc != null) { contentPane.add(cpc,BorderLayout.SOUTH); south = cpc; } else { if (south != null) { contentPane.remove(south); contentPane.validate(); } } pack(); setTitle(file.getName()); } }; player.addControllerListener(listener); player.start();

Page 188: DW & ADBMS-22

} catch(Exception e) { System.out.println("ERROR : ......"+e); } } public static void main(String args[]) { new PlayAudio(); } } // class close

Output

Page 189: DW & ADBMS-22

Practical No:8.3 Concept of multimedia database 8.3 Create a table Singer2 with the attributes sno as singer number, Sname as singer name, Saddress as singer address and video as an audio clip. Also create a table Company2 with attributes Sno,age. Fire the following queries.

i) Find name and age of all the singer.

ii) Find name and video clip of a particular singer.

Output:8.3 Query to Create Singer2 & Company Tables :

Create Table Singer2 ( Sno Number(3), Sname Varchar2(10), Saddress Varchar2(25), Video BLOB ); Create Table Company2 ( Sno Number(5) Age Number(5) );

Column Name Data Type Sno Number

Sname Varchar2(25) Saddress Varchar2(25)

Video BLOB

Field Name Data Type Sno Number(5)

Sname Varchar2(15) Saddress Varchar2(25)

Video BLOB

Field Name Data Type Sno Number(5) Age Number(5)

Page 190: DW & ADBMS-22

Java Program to Insert Video File in to Table Singer2

import java.io.*; import java.sql.*; import javax.swing.*; import java.awt.*; import javax.swing.event.*; import java.awt.event.*; public class AddVideo { public static void main(String[] args) { new AddVideo(); } AddVideo() { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String names[]={"Joe","Steve","John","Justin","Thomas"}; String city[]={"Mumbai","Kolkatta","Chennai","Panji","Hyderabad"};

Connection c = DriverManager.getConnection("jdbc:odbc:DSN26","scott","tiger");

Statement s = c.createStatement(); int i=1; File file; FileInputStream fis; PreparedStatement psmt; for(i=0;i<5;i++) { file = new File((i+1)+".avi"); fis = new FileInputStream(file); psmt=c.prepareStatement("Insert into Singer2 values(?,?,?,?)"); psmt.setInt(1,i+1); psmt.setString(2,names[i]); psmt.setString(3,city[i]); psmt.setBinaryStream(4,fis,(int)file.length()); psmt.executeUpdate(); } System.out.println("Video Files Inserted Successfully"); } catch (Exception e) { e.printStackTrace(); } } }

Page 191: DW & ADBMS-22

i) Find Name and Age of all the Singer.

SQL> Select s1.Sname,s2.Age from Singer2 s1,Company s2 where s1.sno=s2.sno;

SNAME AGE Joe 35

Steve 20 John 25 Justin 45

Thomas 30

ii) Find Name and Video clip of a particular singer. Java Program for retrieving and playing the video file inserted in to the Singer2 import java.io.*; import java.sql.*; import javax.swing.*; import javax.media.*; import java.awt.*; import java.awt.event.*; import java.net.*; import java.io.*; public class PlayVideo extends JFrame { Player player; JTextField txtno=new JTextField(); JTextField txtname=new JTextField(); JLabel lno=new JLabel("SNo. : "); JLabel lname=new JLabel("Name : "); JPanel no=new JPanel(); JPanel name=new JPanel(); JPanel both=new JPanel(); JButton ok=new JButton("OK"); Component center; Component south; Connection c; byte[] bytes; ResultSet rs; ResultSetMetaData rsmd; Statement stmt; String fileName; String path; File outFile; FileOutputStream outStream;

Page 192: DW & ADBMS-22

File file; URL url; Container contentPane; Component cpc; Component vc; public PlayVideo() { contentPane=getContentPane(); no.setBorder(BorderFactory.createTitledBorder(" Enter No ")); no.setLayout(new GridLayout(1,3,5,5)); no.add(lno); no.add(txtno); no.add(ok); name.setBorder(BorderFactory.createTitledBorder("")); name.setLayout(new GridLayout(1,2,5,5)); name.add(lname); name.add(txtname); txtname.setEnabled(true); both.setBorder(BorderFactory.createTitledBorder("")); both.setLayout(new BorderLayout()); both.add(no,BorderLayout.NORTH); both.add(name,BorderLayout.CENTER); contentPane.add(both,BorderLayout.NORTH); setTitle("Play Video"); setSize(200,200); setVisible(true); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { if(player!=null) { player.stop(); } setVisible(false); freeAll(); dispose(); System.exit(0); } }); try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection conn = DriverManager.getConnection("jdbc:odbc:DSN26","scott","tiger"); stmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIV

E, ResultSet.CONCUR_READ_ONLY);

}

Page 193: DW & ADBMS-22

catch(Exception e) { e.printStackTrace(); } ok.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { try { if(player!=null) { player.stop(); }

System.out.println("The Value Entered Is: ++"+txtno.getText()+"++");

Integer no=0; try { no=Integer.parseInt(txtno.getText()); } catch(NumberFormatException nfe) { txtname.setText("Invalid Number!!"); txtno.setText(""); } if(!txtno.getText().equals("")) { System.out.println("Inside..."); System.out.println(no);

rs = stmt.executeQuery("Select sname, video from Singer2 where sno="+no);

rsmd=rs.getMetaData(); rs.first(); try{ txtname.setText(rs.getString("sname")); if(player!=null) { player.stop(); player=null; } contentPane=null; vc=null; putFile(); txtname.setText(""); }

Page 194: DW & ADBMS-22

catch(SQLException s) { txtname.setText("No Data For This Eno."); txtno.setText(""); } try { txtname.setText(rs.getString("sname")); } catch(SQLException e) { txtname.setText("No Data For This Eno."); } } else { txtname.setText("No Data For This Eno."); } } catch(Exception e) { e.printStackTrace(); } } }); } //constructor close void putFile() { try{ bytes=new byte[100]; bytes=rs.getBytes("video"); fileName = new String ( "RetrivedVideo.avi"); path = new String ( "C:\\WINNT\\Temp" ); outFile = new File ( path, fileName ); outStream = new FileOutputStream ( outFile ); System.out.println ( "Writing to file: " + outFile.getName() ); for ( int i = 0; i < bytes.length; i++ ) { try { outStream.write ( bytes [ i ] ); } catch ( IOException e ) { System.out.println("Error: " +e );

Page 195: DW & ADBMS-22

} } System.out.println("length:" +bytes.length); outStream.close (); File f =new File("C:/WINNT/Temp/RetrivedVideo.avi"); load(f); }catch(Exception ae) { System.out.println("ERROR!!!!! : "+ae); } } public void freeAll() { player=null;txtno=null;txtname=null;lno=null; lname=null;no=null;name=null;both=null; ok=null;center=null;south=null; c=null; bytes=null; rs=null;rsmd=null;stmt=null;fileName=null; path=null;outFile=null;outStream=null;file=null;url=null;contentPane=null;cpc=null; } public void load(final File file) { try{ url=file.toURL(); contentPane=getContentPane(); if (player != null) { player.stop(); } player = Manager.createPlayer(url); ControllerListener listener = new ControllerAdapter() { public void realizeComplete(RealizeCompleteEvent event) { vc = player.getVisualComponent(); if (vc != null) { contentPane.add(vc,BorderLayout.CENTER); center = vc; } else { if (center != null) { contentPane.remove(center); contentPane.validate(); } }

Page 196: DW & ADBMS-22

cpc = player.getControlPanelComponent(); if (cpc != null) { contentPane.add(cpc,BorderLayout.SOUTH); south = cpc; } else { if (south != null) { contentPane.remove(south); contentPane.validate(); } } pack(); setTitle(file.getName()); } }; player.addControllerListener(listener); player.start(); } catch(Exception e) { System.out.println("ERROR : ......"+e); } } public static void main(String args[]) { new PlayVideo(); } } // class close

Page 197: DW & ADBMS-22

Output:-