0% found this document useful (0 votes)
17 views54 pages

AD3381 - DBDM Record

dbdm

Uploaded by

sincet72
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views54 pages

AD3381 - DBDM Record

dbdm

Uploaded by

sincet72
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

Ex. No.

: 1
DATABASE DEVELOPMENT LIFE CYCLE
Date:

AIM:
To Analyze, Design and implement the problem and come with the entities in it.
Identifywhat Data has to be persisted in the databases.

Getting started with PostgreSQL:


Download the PostgreSQL software from the given link and install
it. https://www.postgresql.org/download/

Database Development Life cycle:


Life cycle of database begins with analysis and defining of the problems and
objectives. Let us see the steps involved –

Stage of Database
Example of
system Example of Facts
development Lifecycle Documentatio
nProduced
Database Planning Aims and objectives of database Mission statements and
projects. objectives.
System Identification Description of major user views Definition of scope and
(Job roles, business application boundary of database system,
areas). definition ofuser views to be
supported.
Requirements Requirements of user views, User requirement
Collection and system specifications, including specification, system
Analysis performance and security specification.
requirements.
Database design User’s responses to checking the Logical database design, data
logical database design, dictionary, physical database
functionality provided by target design.
DBMS.
Application Design Users’ response to checking Application design.
interface design.
DBMS Selection Functionality provided by target DBMS evaluation
DBMS.
Prototyping User response to prototype. Modified user requirement
specification and system
specification.
Implementation Functionality provided by target
DBMS.
Data conversion and Format of current data, data import
loading capability of target DBMS.
Testing Test Results. Testing strategies used
Operational Performance testing results, new User manual, analysis of
maintenance or changing user and system performance results,
requirements. modified users requirements
and systemspecification.

1
Database Creation and Constraints:
SQL CREATE DATABASE Statement
The CREATE DATABASE statement is used to create a new SQL
database.SyntaxCREATE DATABASE databasename;
Example
CREATE DATABASE testDB;

SQL DROP DATABASE Statement


The DROP DATABASE statement is used to drop an existing SQL database
.SyntaxDROP DATABASE databasename;

Example
DROP DATABASE test DB;

Note: Use the \dt or \dt+ command in psql to show tables in a specific
database.PostgreSQL – Show Tables

PostgreSQL does not support the SHOW TABLES statement directly like
MySQL doesbut provides users with an alternative.
SELECT * FROM table name;

SQL CREATE TABLE Statement

The CREATE TABLE statement is used to create a new table in a database.Syntax


CREATE TABLE table_name (column1 datatype, column2 datatype, column3
datatype,);The column parameters specify the names of the columns of the table.
The datatype parameter specifies the type of data the column can hold (e.g.
varchar, integer, date, etc.).

Example
CREATE TABLE Persons ( PersonID int, LastName varchar(255),
FirstName varchar(255),Address varchar(255), City varchar(255));

Create Table Using Another Table

A copy of an existing table can also be created using CREATE TABLE.


The new table gets the same column definitions. All columns or specific columns
can beselected.
If you create a new table using an existing table, the new table will be filled
with theexisting values fromthe old table.

Syntax
CREATE TABLE new_table_name ASSELECT column1, column2,...
FROM existing_table_name
WHERE ........................ ;
The following SQL creates a new table called "TestTables" (which is a copy
of the"Customers" table):

2
Example
CREATE TABLE TestTable AS SELECT customername, contactnameFROM customers;

SQL DROP TABLE Statement


The DROP TABLE statement is used to drop an existing table in a
database.SyntaxDROP TABLE table_name;SQL TRUNCATE TABLE
The TRUNCATE TABLE statement is used to delete the data inside a table, but
not thetable itself.Syntax
TRUNCATE TABLE table_name;

SQL ALTER TABLE Statement

The ALTER TABLE statement is used to add, delete, or modify columns in an


existingtable.
The ALTER TABLE statement is also used to add and drop various constraints
on anexisting table.

ALTER TABLE - ADD Column


To add a column in a table, use the following syntax:ALTER TABLE table_name
ADD column_name datatype;
The following SQL adds an "Email" column to the "Customers" table: ALTER
TABLE Customers ADD Email varchar(255);

ALTER TABLE - DROP COLUMN


To delete a column in a table, use the following syntax (notice that some database
systemsdon't allowdeleting a column):
ALTER TABLE table_name
DROP COLUMN column_name;
The following SQL deletes the "Email" column from the "Customers" table:
ALTERTABLE Customers
DROP COLUMN Email;

ALTER TABLE - ALTER/MODIFY COLUMN


To change the data type of a column in a table, use the following
syntax:
ALTER TABLE table_name
ALTER COLUMN column_name datatype;
Example
Look at the "Persons" table:

ID LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Now we want to add a column named "DateOfBirth" in the "Persons" table. We


use the following SQL statement:

ALTER TABLE PersonsADD DateOfBirth date;


3
Notice that the new column, "DateOfBirth", is of type date and is going to hold a
date. Thedata typespecifies what type of data the column can hold.
The "Persons" table will now look like this:

ID LastName FirstName Address City DateOfBirth


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Change Data Type Example


Now we want to change the data type of the column named "DateOfBirth" in the
"Persons"table.We use the following SQL statement:
ALTER TABLE Persons
ALTER COLUMN DateOfBirth year;
Notice that the "DateOfBirth" column is now of type year and is going to hold a
year in atwo- or four-digit format.

DROP COLUMN Example


Next, we want to delete the column named "DateOfBirth" in the "Persons" table.
We usethe following SQL statement:
ALTER TABLE Persons DROP COLUMN
DateOfBirth;The "Persons" table will now look
like this:
ID LastName FirstName Address City
1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

SQL Constraints
SQL constraints are used to specify rules for data in a table.SQL Create Constraints
Constraints can be specified when the table is created with the CREATE TABLE
statement, or after thetable is created with the ALTER TABLE statement.

Syntax
CREATE TABLE table_name ( column1 datatype constraint, column2
datatypeconstraint, column3 datatype constraint);

SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a table. This ensures the
accuracy and reliability of the data in the table. If there is any violation between the
constraint and the data action, the action is aborted.
Constraints can be column level or table level. Column level constraints apply to a
column, and table levelconstraints apply to the whole table.
The following constraints are commonly used in SQL:

 NOT NULL - Ensures that a column cannot have a NULL value


 UNIQUE - Ensures that all values in a column are different

 PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely


identifieseach row in a table
4
 FOREIGN KEY - Prevents actions that would destroy links between tables
 CHECK - Ensures that the values in a column satisfies a specific condition
 DEFAULT - Sets a default value for a column if no value is specified
 CREATE INDEX - Used to create and retrieve data from the database very quickly
SQL NOT NULL Constraint
By default, a column can hold NULL values.
The NOT NULL constraint enforces a column to NOT accept NULL values.
This enforces a field to always contain a value, which means that you cannot insert
a newrecord, or updatea record without adding a value to this field.

SQL NOT NULL on CREATE TABLE


The following SQL ensures that the "ID", "LastName", and "FirstName"
columns willNOT accept NULLvalues when the "Persons" table is created:
Example
CREATE TABLE Persons ( ID int NOT NULL, LastName varchar(255) NOT
NULL, FirstName varchar(255) NOT NULL,Age int);

SQL NOT NULL on ALTER TABLE


To create a NOT NULL constraint on the "Age" column when the "Persons" table is
already created, usethe following SQL:
ALTER TABLE Persons MODIFY Age int NOT NULL;

SQL UNIQUE Constraint


The UNIQUE constraint ensures that all values in a column are different.
Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for
uniqueness for a column orset of columns.
A PRIMARY KEY constraint automatically has a UNIQUE constraint.
However, you can have many UNIQUE constraints per table, but only one
PRIMARY KEY constraint pertable.

SQL UNIQUE Constraint on CREATE TABLE


The following SQL creates a UNIQUE constraint on the "ID" column when the
"Persons" table is created: CREATE TABLE Persons (ID int NOT NULL, LastName
varchar(255) NOT NULL, FirstName varchar(255), Age int, UNIQUE (ID));

SQL UNIQUE Constraint on ALTER TABLE


To create a UNIQUE constraint on the "ID" column when the table is already
created, usethe following SQL:
ALTER TABLE Persons ADD UNIQUE (ID);

DROP a UNIQUE Constraint


To drop a UNIQUE constraint, use the following SQL: ALTER TABLE Persons
DROPINDEX UC_Person;

SQL PRIMARY KEY Constraint


The PRIMARY KEY constraint uniquely identifies each record in a table. Primary
keys must contain UNIQUE values, and cannot contain NULL values.

A table can have only ONE primary key; and in the table, this primary key can
consist ofsingle or multiple columns (fields).

5
SQL PRIMARY KEY on CREATE TABLE
The following SQL creates a PRIMARY KEY on the "ID" column when the
"Persons" table is created: CREATE TABLE Persons (ID int NOT NULL, LastName
varchar(255) NOT NULL,FirstName varchar(255), Age int, PRIMARY KEY (ID));

SQL PRIMARY KEY on ALTER TABLE


To create a PRIMARY KEY constraint on the "ID" column when the table is
alreadycreated, use the following SQL:
ALTER TABLE Persons ADD PRIMARY KEY (ID);
To allow naming of a PRIMARY KEY constraint, and for defining a
PRIMARY KEYconstraint on multiple columns, use the following SQL syntax:
ALTER TABLE Persons ADD CONSTRAINT PK_Person PRIMARY KEY
(ID,LastName);

DROP a PRIMARY KEY Constraint


To drop a PRIMARY KEY constraint, use the following SQL:
ALTER TABLE Persons DROP PRIMARY KEY;
The FOREIGN KEY constraint is used to prevent actions that would destroy links
betweentables.
A FOREIGN KEY is a field (or collection of fields) in one table, that refers
to thePRIMARY KEY in another table.
The table with the foreign key is called the child table, and the table with the primary
keyis called the referenced or parent table.
Look at the following two tables:

Persons Table
PersonID LastName FirstName Age
1 Hansen Ola 30
2 Svendson Tove 23

Orders Table
OrderID OrderNumber PersonID
1 77895 3
2 44678 3
3 22456 2
4 24562 1

Notice that the "PersonID" column in the "Orders" table points to the "PersonID"
column in the "Persons"table.
The "PersonID" column in the "Persons" table is the PRIMARY KEY in the
"Persons" table. The "PersonID" column in the "Orders" table is a FOREIGN KEY
in the "Orders" table.

The FOREIGN KEY constraint prevents invalid data from being inserted into the
foreign key column,because it has to be one of the values contained in the parent
table.

6
SQL FOREIGN KEY on CREATE TABLE
The following SQL creates a FOREIGN KEY on the "PersonID" column when the
"Orders" table iscreated:
CREATE TABLE Orders (OrderID int NOT NULL, OrderNumber int NOT
NULL, PersonID int, PRIMARY KEY (OrderID), FOREIGN KEY (PersonID)
REFERENCES
Persons(PersonID)); FOREIGN KEY (PersonID) REFERENCES Persons(PersonID));

RESULT
Thus the creation of database with database was implemented and various constraints was
created and the output was verified successfully.

7
Ex. No.: 2
DATABASE DESIGN USING CONCEPTUAL
Date: MODELING (ER-EER)

AIM:
To create database using conceptual modeling using (ER-EER) model using SQL
workbench.

PROCEDURE:
ENHANCED ENTITY RELATIONSHIP (EER) MODEL:

Enhanced Entity Relationship (EER) Model is a high level data model which
provides extensions to original Entity Relationship (ER) model. EER Models
supports more details design. EER Modeling emerged as a solution for modeling
highly complex databases.

EER uses UML notation. UML is the acronym for Unified Modeling Language;
it is a general purpose modeling language used when designing object oriented
systems. Entities are represented as class diagrams. Relationships are represented
as associations between entities. The diagram shown below illustrates an ER
diagram using the UML notation.

We can deduce from this that the nature of the relationship between members
and payments entities is one-to-many.Now lets create EER model using
MySQL Workbench Inthe MySQL workbench , Click - "+"Button

8
Double click on Add Diagram button to open the workspace for ER diagrams.

Following window appears

9
Let's look at the two objects that we will work with.
The table object allows us to create entities and define the attributes associated
with theparticular entity.

The place relationship button allows us to define relationships

between entities. The members' entity will have the following

attributes
 Membership number
 Full names
 Gender
 Date of birth
 Physical address
 Postal address

Let's now create the members table

1. Drag the table object from the tools panel


2. Drop it in the workspace area. An entity named table 1 appears
3.Doubleclick on it. The properties window shown below appears

10
Next ,
1. Change table 1 to Members
2. Edit the default idtable1 to membership number
3. Click on the next line to add the next field
4. Do the same for all the attributes identified in members' entity.

Your properties window should now look like this.

Repeat the above steps for all the identified entities.


Your diagram workspace should now look like the one shown below.

11
Lets create relationship between Members and Movie Rentals
1. Select the place relationship using existing columns too
2. Click on membership_number in the Members table
3. Click on reference_number in the Movie Rentals table

Repeat above steps for other relationships. Your ER diagram should now look like this –

12
RESULT
Thus the creation of database using conceptual modeling using (ER-EER)
model using SQL workbench was created and the output was verified successfully.

13
Ex.No.: 3
IMPLEMENT THE DATABASE USING SQL DATA
Date: DEFINITION WITH CONSTRAINTS

Aim:
To implement database using SQL Data definition with constraints

Procedure:
Do with pgAdmin application in your PostgreSQL
 Launch pgAdmin 4.
 Let’s create a table by right clicking on Tables and click Table…

 Give your table a name and then click Columns

14
 Click the + symbol to add columns

 Name your column, select the data type, and give a length if needed. Then click Save


Now that you have created a table, view it under the Tables object. Right
click andrefresh if it didn’t update.

15
 Query Tool Example: 
Note: I’m showing you my database with data for demonstration purposes
 When an object is selected under the database tree view menu, you can click the Tools
tab and click Query Tool. Query tool brings up an editor to execute SQL statements.
 You can also right click the database and click Query Tool …

 A tab called query editor will open up on the right. You can write SQL
statements and click the play button to execute. Your results will show below
the editor on the DataOutput tab.

16
CREATE TABLE products(product_no integer,name text,price numeric CHECK
(price>0));
CREATE TABLE product0(product_no integer,name text,price numeric);
CREATE TABLE products0(products_no integer,name text,price numeric DEFAULT
9.99);
CREATE TABLE product(product_no integer NOT NULL,name text NOT
NULL,price numeric);
CREATE TABLE product1(product_no integer UNIQUE,name text,price numeric);
CREATE TABLE product2(product_no integer UNIQUE NOT NULL,name
text,price numeric);
CREATE TABLE example(a integer,b integer,c integer,PRIMARY KEY(a,c));
CREATE TABLE t1(a integer PRIMARY KEY,b integer,c
integer,FOREIGNKEY(b,c)REFERENCES example);

17
INSERT into products
values(1,'Paste',75);
INSERT into products
values(2,'Brush',20);
INSERT into products
values(3,'pen',10);
INSERT into products
values(4,'Pencil',05);

SELECT*from products;

ALTER TABLE products ADD COLUMN


description text;
ALTER TABLE products DROP COLUMN
description;
ALTER TABLE products ADD CONSTRAINT some_name
UNIQUE(product_no);
ALTER TABLE products DROP CONSTRAINT some_name;
ALTER TABLE products ALTER COLUMN price SET DEFAULT 7.77;
ALTER TABLE products ALTER COLUMN price TYPE
numeric(10,2);
ALTER TABLE products RENAME COLUMN product_no TO
product_number; ALTER TABLE products RENAME TO items;

18
RESULT
Thus the implementation of database using SQL Data definition with constraints was
created and the output was verified successfully.

19
Ex.No.: 4
QUERY THE DATABASE USING SQL MANIPULATION
Date:

Aim:
To query the database using SQL Data Manipulation commands
Procedure:
SQL Statements
Most of the actions you need to perform on a database are done with SQL
statements.The following SQL statement selects all the records in the
"Customers" table:
SELECT * FROM Customers;
Semicolon after SQL Statements?
Some database systems require a semicolon at the end of each SQL statement.
Semicolon is the standard way to separate each SQL statement in database
systems that allow more than one SQLstatement to be executed in the same call
to the server.
In this tutorial, we will use semicolon at the end of each SQL statement.Some
of The MostImportant SQL Commands

 SELECT - extracts data from a database


 UPDATE - updates data in a database
 DELETE - deletes data from a database
 INSERT INTO - inserts new data into a database
 CREATE DATABASE - creates a new database
 ALTER DATABASE - modifies a database
 CREATE TABLE - creates a new table
 ALTER TABLE - modifies a table
 DROP TABLE - deletes a table
 CREATE INDEX - creates an index (search key)
 DROP INDEX - deletes an index
CREATE TABLE products(no integer,name text,cost numeric);

INSERT into products values(2,'Paste',55);


INSERT into products values(3,'Soap',70);
INSERT into products values(4,'Shampoo',105);

20
SELECT*from products;

SELECT DISTINCT no from products;

SELECT DISTINCT name from products;

SELECT*from products where no=2;

21
SELECT no,name from products where no=1 and cost=20;

SELECT no,name from products where no=2 or cost=55;

SELECT no,name from products where not no=1;

SELECT no,name from products order by no desc;

SELECT no from products where no is null;

22
SELECT no from products where no is not null;

update products set no=0 where cost=45;

delete from products where no=0;

SELECT min(no) from products where no=1;

SELECT max(cost) from products where no=1;

23
SELECT count(no) from products;

SELECT avg(cost) from products;

SELECT sum(no) from products;

SELECT no from products where no in(1,2);

SELECT *from products where cost not in(1,3);

24
SELECT *from products where cost between 40 and 80;

SELECT *from products where cost not between 40 and 80;

RESULT
Thus the querying database using SQL Data Manipulation commands was created
and the output was verified successfully.

25
Ex.No.: 5 QUERYING / MANAGING THE DATABASE USING
SQL PROGRAMMING STORED PROCEDURES /
FUNCTIONS, CONSTRAINTS AND SECURITY USING
Date: TRIGGERS

Aim:
To Querying/Managing the database using SQL Programming – Stored
Procedures /Functions – Constraints and security using Triggers
Procedure:
SQL Stored Procedures for SQL Server What is a Stored Procedure?
A stored procedure is a prepared SQL code that you can save, so the code can
be reusedover and over again.
So if you have an SQL query that you write over and over again, save it
as a storedprocedure, and then just call itto execute it.
You can also pass parameters to a stored procedure, so that the stored
procedure can act based on the parametervalue(s) that is passed.

CREATE TABLE employee(ID int,first_name varchar(40) not null,last_name


varchar(40) not null,primary key(ID));
CREATE TABLE employee_audit(ID int,employee_id int not
null,last_namevarchar(40)not null,changed_on timestamp(6) not
null);

SELECT *FROM employee;

SELECT *FROM employee_audit;

26
CREATE OR REPLACE FUNCTION
log_last_name_changes() returns trigger
language
PLPGSQL
as
$$
BEGIN
if NEW.last_name<>OLD.last_name then INSERT into
employee_audit(employee_id,last_name,changed_on)values(OLD.ID,OLD.last_n
ame,NOW());
END if;
return new;
END;
$$

CREATE trigger last_name_changes


before update
on employee for each row
execute procedure log_last_name_changes();

INSERT into employee VALUES(101,'John','Doe');


INSERT into employee VALUES(102,'Lily','Bush');

SELECT *FROM employee;

27
UPDATE employee set last_name='Brown' WHERE ID=102;

SELECT *FROM employee;

SELECT *FROM employee_audit;

RESULT
Thus the Querying/Managing the database using SQL Programming – Stored
Procedures /Functions – Constraints and security using Triggers was created and the
output was verified successfully.

28
Ex.no: 6 DATABASE DESIGN USING
NORMALIZATION
Date:

AIM:
Apply the database Normalization techniques for designing relational database
tables to minimize duplication of information like 1NF, 2NF, 3NF, BCNF and
for creating relationship between the databases as tables using SQL commands.

PROCEDURE
Normalization is a database design technique which organizes tables in a manner
that reduces redundancy and dependency of data.

It divides larger tables to smaller tables and links them using relationships.

The inventor of the relational model Edgar Codd proposed the theory of
normalizationwith the introduction of First Normal Form, and he continued to
extend theory with Second and Third Normal Form. Later he joined with
Raymond F. Boyce to develop the theory of Boyce-Codd Normal Form.

Theory of Data Normalization in SQL is still being developed further. For


example, there are discussions even on 6thNormal Form. However, in most
practical applications, normalization achieves its best in 3rd Normal Form.
The evolution of Normalization theories is illustrated below-

Database Normalization Examples -

Assume a video library maintains a database of movies rented out.


Without anynormalization, all information is stored in one table as
shown below.

1NF (First Normal Form) Rules


 Each table cell should contain a single value.
 Each record needs to be unique.

29
1NF Example

Table 1: In 1NF Form

2NF (Second Normal Form) Rules

 Rule 1- Be in 1NF
 Rule 2- Single Column Primary Key

Table 1

Table 2

We have divided our 1NF table into two tables viz. Table 1 and Table2.
Table 1 contains member information. Table 2 contains information on movies rented.
We have introduced a new column called Membership_id which is the
primary key fortable 1.Records can be uniquely identified in Table 1 using
membership id.
Database - Foreign Key

In Table 2, Membership_ID is the Foreign Key

30
3NF (Third Normal Form) Rules
 Rule 1- Be in 2NF
 Rule 2- Has no transitive functional dependencies
To move our 2NF table into 3NF, we again need to again divide our table.

3NF Example

Table 1

Table 2

Table 3

Boyce-Codd Normal Form (BCNF)

Even when a database is in 3rd Normal Form, still there would be anomalies
resulted if it has more than one Candidate Key.
Sometimes is BCNF is also referred as 3.5 Normal Form. 4NF (Fourth
Normal Form)Rules
5NF (Fifth Normal Form) Rules

A table is in 5th Normal Form only if it is in 4NF and it cannot be


decomposed into anynumber of smaller tables without loss of data.
6NF (Sixth Normal Form) Proposed

6th Normal Form is not standardized, yet however, it is being discussed by


database expertsfor sometime. Hopefully, we would have a clear & standardized
definition for 6th Normal Form in the near future...

31
RESULT
Thus the database design using normalization was created and the output was
verified successfully.

32
Ex. No.: 7
DEVELOPMENT OF DATABASE APPLICATIONS
USING NETBEANS
Date:
AIM
To develop a database application using NetBeans.

IMPLEMENTION
Creating Application using Netbeans
Step 1: click services > database > java DB > right click > create database.
Then create java DB database box is popped.
Step 2: give database name > give user name as PECAI&DS > set password
as PECAI&DS > click OK button.

The java DB database will start to process. Once the process is stopped, the java
DB will becreated.
Step 3: select the created one > right click > connect

33
Once you are connected, you can see the database list.
Step 4: select test > tables > create table > give table name

Step 5: click add column button > give name > select type > give size > then
click OKbutton

If you want more columns, you can repeat this step 5and add columns. Then
the table willbe created.

34
Step 6: at the top corner, select project. In the empty space under project, right click.

Step 7: select new project > java > java application > click NEXT

Step 8: give project name > remove tick in create main class > click
FINISHSo, the project will be created under the project menu.

35
Step 9: click the project you created. Under that, click source packages > default package
> new >java package> give package name > click finish.
The package will be created in the source package under your project.

Step 10: click the package created under source package > new >
JFrame Form > A new JFrame form window will be popped. Give

class name and click finish.


Step 11: This window will be shown. Click panel (if you want
you canresize it). Then click properties and start doing designing
your application.

36
37
38
RESULT
Thus the developing a database application using NetBeans was created and
the output was verified successfully.

39
Ex. No.:8
DATABASE DESIGN USING EER-TO-ODB
MAPPING / UML CLASS DIAGRAMS
Date:

AIM:
To create ER/ UML diagram of a database using MySQL workbench

PROCEDURE:
Step 1: First make sure you have a Database and Tables created on the
MySQLserver.
For Example :-
Database - bank.
Tables - account, branch, customer, loan, trandetails
QUERYING/MANAGING THE DATABASE USING SQL PROGRAMMING
 STORED PROCEDURES/FUNCTIONS
 CONSTRAINTS AND SECURITY USING TRIGGERS

.
Step 2: Click on Database -> Reverse Engineer.

40
Step 3: Select your stored connection (for connecting to your MySQL Server in
whichdatabase is present) from the dropdown. Then click Next.

Step 4: After the execution gets completed successfully (connection to DBMS), click Next.

41
Step 5: Select your Database from the MySQL Server for which you want to
create the ERDiagram(in our case the database name is “bank”), then click Next.

Step 6: After the retrieval gets completed successfully for the selected Database, click
Next.

42
Step 7: Select the Tables of the Database which you want to be visible on the
ERDiagram (In this case I am importing all the tables of the DB), then click
Execute>.

Step 8: After the Reverse Engineering Process gets completed successfully, click Next.

43
Step 9: Click Finish.

44
RESULT
Thus the creation of ER/ UML diagram of a database using MySQL
workbench was created and the output was verified successfully.

45
Ex. No.:9
USER-DEFINED TYPES IN SQLSERVER
Date:

AIM:
Creating datas using User-Defined Types (UDTs) in SQL server.

PROCEDURE:
You can access user-defined type (UDT) functionality in Microsoft SQL Server
from the Transact- SQL language by using regular query syntax. UDTs can be
used in thedefinitionof database objects, as variables in Transact-SQL batches,
in functions and stored procedures, and as arguments in functions and stored
procedures.
 Defining UDT Tables and Columns
Describes how to use Transact-SQL to create a UDT column in a table.
 Manipulating UDT Data
Describes how to use Transact-SQL to work with UDT data in SQL Server.

 Defining UDT Tables and


Columns CREATING
TABLES WITH UDTS

There is no special syntax for creating a UDT column in a table. You can
use the name of the UDT in a column definition as though it were one of the
intrinsic SQL Server data types. The following CREATE TABLE Transact-SQL
statement creates a table named Points, with a column named ID, which is
defined as an int identity column and the primary key for the table. The second
column is namedPointValue, witha data type of Point. The schema name used
in this exampleis dbo. Note that you must have the necessary permissions to
specify a schema name. If you omit the schema name, the default schema for the
database user is used.

CREATE TABLE dbo.Points


(ID int IDENTITY(1,1) PRIMARY KEY, PointValue Point)
 Manipulating UDT Data
 Inserting Data in a UDT Column

The following Transact-SQL statements insert three rows of sample data into
the Points table. The Point data type consists of X and Y integer values that are
exposed as propertiesof the UDT. You must use either the CAST or CONVERT
function to cast the comma- delimited X and Y values to the Point type. The
first two statements use the CONVERT function to convert a string value to the
Point type, and the third statement uses the CAST function:

INSERT INTO dbo.Points (PointValue) VALUES (CONVERT(Point, '3,4'));


INSERT INTO dbo.Points(PointValue) VALUES (CONVERT(Point, '1,5'));
INSERTINTO dbo.Points (PointValue) VALUES (CAST ('1,99' AS Point));

46
SELECTING DATA

The following SELECT statement selects the binary value

of the UDT.SQLCopy
SELECT ID, PointValue FROM dbo.Points

To see the output displayed in a readable format, call the ToString


method ofthe Point UDT, which converts the value to its string
representation.

SQLCopy
SELECT ID, PointValue.ToString() AS
PointValueFROM dbo.Points;

This produces the

following results. Copy


ID PointValue

1 3,4
2 1,5
3 1,99

You can also use the Transact-SQL CAST and CONVERT functions to
achieve the sameresults.

SQLCopy
SELECT ID, CAST(PointValue
AS varchar) FROM dbo.Points;

SELECT ID, CONVERT(varchar,


PointValue) FROM dbo.Points;

The Point UDT exposes its X and Y coordinates as properties, which you can
then select individually. The following Transact-SQL statement selects the X
and Y coordinates separately:

SQLCopy
SELECT ID, PointValue.X AS xVal,
PointValue.Y AS yValFROM dbo.Points;

The X and Y properties return an integer value, which is displayed in

the result set. Copy


ID xVal yVal

1 3 4
2 1 5
3 1 99

47
WORKING WITH VARIABLES

You can work with variables using the DECLARE statement to assign a
variable to a UDTtype. The following statements assign a value using the
Transact-SQL SET statement and display the results by calling the UDT's
ToString method on the variable:

SQLCopy
DECLARE @PointValue Point;
SET @PointValue = (SELECT PointValue FROM
dbo.PointsWHERE ID = 2);
SELECT @PointValue.ToString() AS PointValue;

The result set displays the variable value:

Copy
PointValue

-1,5

The following Transact-SQL statements achieve the same result using SELECT
rather thanSET for the variable assignment:

SQLCopy
DECLARE @PointValue Point;
SELECT @PointValue = PointValue FROM
dbo.PointsWHERE ID = 2;
SELECT @PointValue.ToString() AS PointValue;

The difference between using SELECT and SET for variable assignment is that
SELECT allows you to assign multiple variables in one SELECT statement,
whereas the SET syntaxrequires each variable assignment to have its own SET
statement.

COMPARING DATA

You can use comparison operators to compare values in your UDT if you
have set the IsByteOrdered property to true when defining the class.
For more information, see Creating a User-Defined Type.

SQLCopy
SELECT ID, PointValue.ToString()
AS PointsFROM dbo.Points
WHERE PointValue > CONVERT(Point, '2,2');

You can compare internal values of the UDT regardless of the IsByteOrdered
setting if the values themselves are comparable. The following Transact-SQL
statement selects rows where X is greater than Y:

48
SQLCopy
SELECT ID, PointValue.ToString() AS PointValue
FROM dbo.Points
WHERE PointValue.X < PointValue.Y;

You can also use comparison operators with variables, as shown in this query
that searches for a matching PointValue.

SQLCopy
DECLARE @ComparePoint Point;
SET @ComparePoint = CONVERT(Point,
'3,4'); SELECT ID, PointValue.ToString()
AS MatchingPoint FROM dbo.Points
WHERE PointValue = @ComparePoint;

INVOKING UDT METHODS

You can also invoke methods that are defined in your UDT in Transact-SQL.
The Point class contains three methods, Distance, DistanceFrom, and
DistanceFromXY. For the code listings defining these three methods, see
Coding User-Defined Types.

The following Transact-SQL statement calls the PointValue.Distance method:

SQLCopy
SELECT ID, PointValue.X AS
[Point.X], PointValue.Y AS
[Point.Y], PointValue.Distance()
AS DistanceFromZero
FROM dbo.Points;

The results are displayed in the

Distance column:Copy
ID X Y Distance

1 3 4 5
2 1 5 5.09901951359278
3 1 99 99.0050503762308

The DistanceFrom method takes an argument of Point data type, and displays
the distance from the specified point to the PointValue:

SQLCopy
SELECT ID, PointValue.ToString() AS Pnt,
PointValue.DistanceFrom(CONVERT(Point, '1,99')) AS
DistanceFromPoint
FROM dbo.Points;

49
The results display the results of the DistanceFrom method for each row

in the table:Copy
ID Pnt DistanceFromPoint

1 3,4 95.0210502993942
2 1,5 94
3 1,9 90

The DistanceFromXY method takes the points individually as arguments:

SQLCopy
SELECT ID, PointValue.X as X, PointValue.Y
as Y, PointValue.DistanceFromXY(1, 99) AS
DistanceFromXY FROM dbo.Points

The result set is the same as the DistanceFrom method.

UPDATING DATA IN A UDT COLUMN

To update data in a UDT column, use the Transact-SQL UPDATE statement.


You can also use a method of the UDT to update the state of the object. The
following Transact-SQL statement updates a single row in the table:

SQLCopy
UPDATE dbo.Points
SET PointValue = CAST('1,88'
AS Point) WHERE ID = 3

You can also update UDT elements separately. The following Transact-
SQL statement updates only the Y coordinate:

SQLCopy
UPDATE
dbo.Points
SET
PointValue.
Y = 99
WHERE ID
=3

If the UDT has been defined with byte ordering set to true, Transact-SQL can
evaluate theUDT column in a WHERE clause.

50
SQLCopy
UPDATE
dbo.Points
SET
PointValue =
'4,5'
WHERE PointValue = '3,4';

UPDATING LIMITATIONS

You cannot update multiple properties at once using Transact-SQL. For


example, the following UPDATE statement fails with an error because you
cannot use the same column name twice in one UPDATE statement.

SQLCopy
UPDATE dbo.Points
SET PointValue.X = 5,
PointValue.Y = 99WHERE ID = 3
To update each point individually, you would need to create a mutator method in
the Point UDT assembly. You can then invoke the mutator method to update the
object in a Transact-SQL UPDATE statement, as in the following:

SQLCopy
UPDATE dbo.Points
SET PointValue.SetXY(5, 99) WHERE ID=3

DELETING DATA IN A UDT COLUMN

To delete data in a UDT, use the Transact-SQL DELETE statement. The


following statement deletes all rows in the table that match the criteria specified
in the WHERE clause. If you omit the WHERE clause in a DELETE statement,
all rows in the table will be deleted.

SQLCopy
DELETE FROM dbo.Points
WHERE PointValue = CAST('1,99' AS Point)

Use the UPDATE statement if you want to remove the values in a UDT
column while leaving other row values intact. This example sets the
PointValue to null.

SQLCopy
UPDATE
dbo.Points
SET
PointValue
= null
WHERE ID
=2

51
RESULT
Thus the creation of data using User-Defined Types (UDTs) in SQL server was
created and the output was verified successfully.

52
Ex. No.:10
QUERYING THE OBJECT-RELATIONAL
DATABASEUSING OBJECT
Date: QUERYLANGUAGE

AIM:
Querying object-relational database using object query language.

PROCEDURE:
OQL is a powerful and easy-to-use SQL-like query language with special
features dealingwith complex objects, values and methods

Example:
The following is the sample query:
“what are the names of the black product?” Firstly, create table and
insert columns. Then,
Select distinct p.name From products p Where p.color= ”black”

The above is valid for both SQL and OQL, but the results are different.

53
RESULT
Thus the Querying object-relational database using object query language was
created and the output was verified successfully.

54

You might also like