Full Manual Databse Practices

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 46

SURYA GROUP OF INSTITUTIONS

SURYA SCHOOL OF ENGINEERING & TECHNOLOGY

PRACTICAL RECORD NOTEBOOK

Name of the Student : ………………………………………………………

Register Number : ………………………………………………………

Year & Semester : ………………………………………………………

B.E/M.E & Dept : ………………………………………………………

Subject code : CP4152

Subject Name : Database Practices Laboratory

BONA FIDE CERTIFICATE

This is to Certify that the bona fide record of practical work done in
the Computer Laboratory of Surya School of Engineering & Technology
during the academic year 2023-2024

Subject In charge Head of the Department

Submitted for Anna University Practical Examination held on ……………

Internal Examiner External Examiner


INDEX

Staff
Ex.No. Date Name of the Experiment Page no. Signature
Ex.no. 1a
Data Definition Language

Aim

To create, alter and drop table by using SQL and view them,
enforce the primary key, foreign key, check, unique and not null
constraints

SQL Commands

(i) CREATE TABLE

CREATE TABLE Student (Admno integer, Name char(20), Gender


char(1), Age integer, Place char(10));

(ii) ALTER COMMAND

ALTER TABLE Student ADD Address char;

ALTER TABLE Student RENAME Address TO City;

(iii) DROP TABLE COMMAND

DROP TABLE Student;

(iv) UNIQUE AND NOT NULL CONSTRAINT

CREATE TABLE Student ( Admno integer NOT NULL UNIQUE,


→ Unique constraint Name char (20) NOT NULL, Gender
char (1), Age integer, Place char (10), );

(v) PRIMARY KEY CONSTRAINT

This constraint declares a field as a Primary key which helps to


uniquely identify a record.

CREATE TABLE Student ( Admno integer NOT NULL


PRIMARY KEY, →Primary Key constraint Name
char(20)NOT NULL, Gender char(1), Age integer, Place
char(10), );
(vi) CHECK CONSTRAINT

This constraint helps to set a limit value placed for a field. When
we define a check constraint on a single column, it allows only the restricted
values on that field.

CREATE TABLE Student ( Admno integer NOT NULL PRIMARY


KEY Name char(20)NOT NULL, Gender char(1), Age
integer (CHECK<=19), → Check Constraint Place
char(10), );

(vii) CREATING VIEWS

A view can contain all rows of a table or select rows from a table.
A view can be created from one or many tables which depends on the written
SQL query to create a view.

CREATE VIEW Student_View AS SELECT name, age FROM


Student;

RESULT

Thus the SQL commands for create, alter, drop and Constraints are
implemented successfully
Ex.no. 1b
Data Manipulation Language

Aim:
To insert, Delete, Update the details in a table and
implement aggregate functions, set operations, Nested queries using SQL
commands

SQL Commands

(i) INSERT command


The INSERT command helps to add new data to the database or add new
records to the table.
INSERT INTO Student (Admno, Name, Gender, Age, Place)
VALUES (100,‟ Ashish‟,‟ M‟, 17,‟ Chennai‟);
INSERT INTO Student (Admno, Name, Gender, Age, Place)
VALUES (102, „Adarsh‟, „M‟, 18, „Delhi‟);
INSERT INTO Student VALUES ( 102, „Akshith‟, „M‟, „17,‟ „Bangalore‟);
INSERT INTO Student(Admno, Name, Place)
VALUES (103, „Ayush‟, „Delhi‟);
INSERT INTO Student(Admno, Name, Place)
VALUES (104, „Abinandh‟, „Chennai‟);

(ii) DELETE COMMAND

The DELETE command permanently removes one or more records


from the table. It removes the entire row, not individual fields of the row, so no
field argument is needed.

DELETE FROM Student WHERE Admno=104;


104 Abinandh M 18 Chennai  this record is deleted from student table

DELETE * FROM Student;

The entire table will be empty now

(iii) UPDATE COMMAND

The UPDATE command updates some or all data values in a database. It


can update one or more records in a table.

UPDATE Student SET Age = 20 WHERE Place = “Bangalore”;

The table will be as updated as below:

AGGREGATE FUNCTIONS

SQL aggregate functions including AVG(), COUNT(), MIN(), MAX()


and SUM() functions.

AVG() function to calculate the average of all values while


the DISTINCT keyword forces the function to operate on distinct values only. By
default, the ALL option is used.

SELECT department_ name, ROUND(AVG(salary), 0) avg_salary

FROM employees INNER JOIN departments USING (department_id)

GROUP BY department_ name ORDER BY department_name;


The MIN() function returns the minimum value of a set.

SELECT department_name, MIN(salary) min_salary

FROM employees INNER JOIN departments USING (department_id)

GROUP BY department_name ORDER BY department_name;

The MAX() function returns the maximum value of a set.

SELECT department_name, MAX(salary) highest_salary FROM

Employees INNER JOIN departments USING (department_id)

GROUP BY department_name ORDER BY department_name;

The COUNT() function returns the number of items in a set.

SELECT department_name, COUNT(*) headcount FROM employees


INNER JOIN departments USING (department_id) GROUP BY
department_name ORDER BY department_name;
The SUM() function returns the sum of all values.

SELECT department_id, SUM(salary) FROM employees


GROUP BY department_id;

SET OPERATIONS

1. Union
The SQL Union operation is used to combine the result of two or more SQL
SELECT queries.
SELECT * FROM First UNION SELECT * FROM Second;

2. Union All

Union All operation is equal to the Union operation. It returns the set without
removing duplication and sorting the data.

SELECT * FROM First UNION ALL SELECT * FROM Second;

3. Intersect
It is used to combine two SELECT statements. The Intersect operation returns
the common rows from both the SELECT statements.

SELECT * FROM First INTERSECT SELECT * FROM Second;


4. Minus
It combines the result of two SELECT statements. Minus operator is used to
display the rows which are present in the first query but absent in the second
query.

SELECT * FROM First MINUS SELECT * FROM Second;

Nested Queries
1. IN

Select all employees who won an award.

SELECT id, name FROM employees WHERE id IN (SELECT employee_id


FROM awards);

2. NOT IN

Select all employees who never won an award.

SELECT id, name FROM employees WHERE id NOT IN (SELECT


employee_id) FROM awards);
3. ALL

Select all Developers who earn more than all the Managers

SELECT * FROM employees WHERE role = 'Developer'


AND salary > ALL (SELECT salary FROM employees
WHERE role = 'Manager');

4. ANY

Select all Developers who earn more than any Manager

SELECT * FROM employees WHERE role = 'Developer' AND salary > ANY
(SELECT salary FROM employees WHERE role = 'Manager');

RESULT

Thus the SQL commands for insert, delete, Update, aggregate operations,
Set operations and Nested Queries are implemented successfully
Ex.no. 1c
Transaction Control Language

Aim:
To Commit, Roll back and save point in a table using SQL
commands

SQL Commands
(i) COMMIT command
The COMMIT command is used to permanently save any transaction to
the database. When any DML commands like INSERT, UPDATE, DELETE
commands are used, the changes made by these commands are not permanent.
COMMIT;
(ii) ROLLBACK command
The ROLLBACK command restores the database to the last commited state. It
is used with SAVEPOINT command to jump to a particular savepoint location.
ROLL BACK TO save point name;
(iii) SAVEPOINT command
The SAVEPOINT command is used to temporarily save a transaction so that
you can rollback to the point whenever required. The different states of our table can
be saved at anytime using different names and the rollback to that state can be done
using the ROLLBACK command.

SAVEPOINT savepoint_name;
Example showing COMMIT, SAVEPOINT and ROLLBACK in the student table
having the following data:
INSERT INTO Student VALUES (107, 'Beena', 'F', 20 , 'Cochin'); COMMIT;

UPDATE Student SET Name = „Mini‟ WHERE Admno=105;


SAVEPOINT A;

INSERT INTO Student VALUES(106, 'Jisha', 'F', 19, 'Delhi');


SAVEPOINT B;
ROLLBACK TO A;

RESULT

Thus the SQL commands for commit, Rollback and save point in a table
was implemented successfully
Ex.no. 2a
Distributed Database Design

Aim
To implement and design the distributed data base

Distributed database
A distributed database is basically a database that is not limited to one system, it is
spread over different sites, i.e, on multiple computers or over a network of
computers. A distributed database system is located on various sites that don‟t share
physical components.

Distributed Data Storage :


There are 2 ways in which data can be stored on different sites.
These are:

1. Data Replication
Data replication is the process of storing separate copies of the database at two
or more sites
Some commonly used replication techniques are −

 Snapshot replication
 Near-real-time replication
 Pull replication

Fragmentation
Fragmentation is the task of dividing a table into a set of smaller tables. The
subsets of the table are called fragments. Fragmentation can be of three types:
horizontal, vertical, and hybrid

Vertical Fragmentation
In vertical fragmentation, the fields or columns of a table are grouped into
fragments.
For example, let us consider that a University database keeps records of all
registered students in a Student table having the following schema.
STUDENT

Now, the fees details are maintained in the accounts section. In this case, the
designer will fragment the database as follows −

CREATE TABLE STD_FEES AS SELECT Regd_No, Fees FROM STUDENT;


Horizontal Fragmentation
Horizontal fragmentation groups the tuples of a table in accordance to values
of one or more fields.
For example, in the student schema, if the details of all students of Computer
Science Course needs to be maintained at the School of Computer Science, then the
designer will horizontally fragment the database as follows −
CREATE COMP_STD AS SELECT * FROM STUDENT
WHERE COURSE = "Computer Science";

Hybrid Fragmentation
In hybrid fragmentation, a combination of horizontal and vertical
fragmentation techniques are used.

RESULT

Thus the Distributed Data Base Design and implementation was


successfully
Ex.no. 2b
Row level and Statement level Triggers

Aim
To implement Row level and statement level triggers using SQL commands

Statement-level triggers

A statement-level trigger is fired whenever a trigger event occurs on a table


regardless of how many rows are affected. In other words, a statement-level trigger
executes once for each transaction.

CREATE TRIGGER

We‟ll use the table customers from the sample database for the demonstration:

CREATE OR REPLACE TRIGGER customers_credit_trg


BEFORE UPDATE OF credit_limit
ON customers
DECLARE
l_day_of_month NUMBER;
BEGIN
-- determine the transaction type
l_day_of_month := EXTRACT(DAY FROM sysdate);
IF l_day_of_month BETWEEN 28 AND 31 THEN
raise_application_error(-20100,'Cannot update customer credit from 28th to 31st');
END IF;
END;

A row-level trigger

row-level trigger fires once for each row that is affected by a triggering event.
For example, if deletion is defined as a triggering event for a particular table, and a
single DELETE statement deletes five rows from that table, the trigger fires five
times, once for each row.

We‟ll use the customers table from the sample database for demonstration:
CREATE OR REPLACE TRIGGER customers_update_credit_trg

BEFORE UPDATE OF credit_limit

ON customers

FOR EACH ROW

WHEN (NEW.credit_limit > 0)

BEGIN

-- check the credit limit

IF :NEW.credit_limit >= 2 * :OLD.credit_limit THEN

raise_application_error(-20101,'The new credit ' || :NEW.credit_limit ||

' cannot increase to more than double, the current credit ' || :OLD.credit_limit);

END IF;

END;

The :OLD & :NEW column values

Because row-level triggers execute within the context of a single row, you can
access the old and new column values

IF :NEW.credit_limit > :OLD.credit_limit THEN

-- carry an action
END;
RESULT

Thus the Row level and statement level triggers are implemented
successfully
Ex.no. 2c
Accessing a relational data base using PHP, Python and R

Aim
To accessing a relational data base using PHP, Python and R

Accessing a relational data base using PHP


PHP provides in-built support in the form of predefined functions. To establish
a connection with the MYSQL server, use the function mysql_connect which accepts
three optional parameters.

First parameter is the server name,

Second parameter is the MYSQL server‟s user name

Third parameter is the password for MYSQL server.

Below example demonstrates user validation against the details stored in a


database using PHP and MYSQL:

//HTML Code

<html>

<head>

<title>Login Form</title>

</head>

<body>

<form action="getdb.php" method="get">

<label>Username: </label>

<input type="text" name="user" /><br />

<label>Password: </label>

<input type="password" name="pass" /><br />

<input type="submit" value="Submit" />

<input type="reset" value="Clear" />

</form>

</body>

</html>

//PHP Code - getdb.php

<?php
$utext = $_REQUEST["user"];

$ptext = $_REQUEST["pass"];

$flag = false;

$hostname = "localhost";

$username = "root";

$password = "123456";

$con = mysqli_connect($hostname, $username, $password) or die(mysql_error());

mysqli_select_db($con, "myapp") or die(mysql_error());

$result = mysqli_query($con, "select * from users") or die(mysql_error());

while($x = mysqli_fetch_array($result))

if($utext == $x["uname"] && $ptext == $x["pwd"])

$flag = true;

if($flag)

echo "Valid user!";

else

echo "Invalid username or password!";

?>

Python - MySQL Database Access

The Python standard for database interfaces is the Python DB-API.


Most Python database interfaces adhere to this standard.
You can choose the right database for your application.
Python Database API supports a wide range of database servers such as −
 GadFly
 mSQL
 MySQL
 PostgreSQL
 Microsoft SQL Server 2000
 Informix
 Interbase
 Oracle
 Sybase

To install MySQLdb module, use the following command −


For Ubuntu, use the following command -
$ sudo apt-get install python-pip python-dev libmysqlclient-dev
For Fedora, use the following command -
$ sudo dnf install python python-devel mysql-devel redhat-rpm-config gcc
For Python command prompt, use the following command -
pip install MySQL-python

Database Connection
Following is the example of connecting with MySQL database "TESTDB"
#!/usr/bin/python

import MySQLdb

# Open database connection


db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

# execute SQL query using execute() method.


cursor.execute("SELECT VERSION()")

# Fetch a single row using fetchone() method.


data = cursor.fetchone()
print "Database version : %s " % data

# disconnect from server


db.close()

create Database table EMPLOYEE −


#!/usr/bin/python
import MySQLdb

# Open database connection


db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

# Drop table if it already exist using execute() method.


cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")

# Create table as per requirement


sql = """CREATE TABLE EMPLOYEE (FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),AGE INT,SEX CHAR(1),INCOME FLOAT )"""

cursor.execute(sql)

# disconnect from server


db.close()

INSERT Operation
It is required when you want to create your records into a database table.
executes SQL INSERT statement to create a record into EMPLOYEE table
#!/usr/bin/python

import MySQLdb

# Open database connection


db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

# Prepare SQL query to INSERT a record into the database.


sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()

# disconnect from server


db.close()
Following code segment is another form of execution where you can pass parameters
directly −
..................................
user_id = "test123"
password = "password"

con.execute('insert into Login values("%s", "%s")' % \


(user_id, password))
..................................

READ Operation
READ Operation on any database means to fetch some useful information
from the database.
Once our database connection is established, you are ready to make a query
into this database. You can use either fetchone() method to fetch single record
or fetchall() method to fetech multiple values from a database table.
The following procedure queries all the records from EMPLOYEE table
having salary more than 1000 −
#!/usr/bin/python

import MySQLdb

# Open database connection


db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

sql = "SELECT * FROM EMPLOYEE \


WHERE INCOME > '%d'" % (1000)
try:
# Execute the SQL command
cursor.execute(sql)
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
fname = row[0]
lname = row[1]
age = row[2]
sex = row[3]
income = row[4]
# Now print fetched result
print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
(fname, lname, age, sex, income )
except:
print "Error: unable to fecth data"

# disconnect from server


db.close()
This will produce the following result −
fname=Mac, lname=Mohan, age=20, sex=M, income=2000

Update Operation
UPDATE Operation on any database means to update one or more records,
which are already available in the database.
The following procedure updates all the records having SEX as 'M'. Here, we
increase AGE of all the males by one year.
Example
#!/usr/bin/python

import MySQLdb

# Open database connection


db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

# Prepare SQL query to UPDATE required records


sql = "UPDATE EMPLOYEE SET AGE = AGE + 1
WHERE SEX = '%c'" % ('M')
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()

# disconnect from server


db.close()

DELETE Operation
DELETE operation is required when you want to delete some records from
your database. Following is the procedure to delete all the records from EMPLOYEE
where AGE is more than 20 −
Example
#!/usr/bin/python

import MySQLdb

# Open database connection


db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method


cursor = db.cursor()

# Prepare SQL query to DELETE required records


sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
R - Databases
RMySQL Package
R has a built-in package named "RMySQL" which provides native
connectivity between with MySql database. You can install this package in the R
environment using the following command.
install.packages("RMySQL")

Connecting R to MySql
Once the package is installed we create a connection object in R to connect to
the database. It takes the username, password, database name and host name as input.
# Create a connection Object to MySQL database.
# We will connect to the sampel database named "sakila" that comes with MySql
installation.
mysqlconnection = dbConnect(MySQL(), user = 'root', password = '', dbname = 'sakila',
host = 'localhost')

# List the tables available in this database.


dbListTables(mysqlconnection)

When we execute the above code, it produces the following result −


[1] "actor" "actor_info"
[3] "address" "category"
[5] "city" "country"
[7] "customer" "customer_list"
[9] "film" "film_actor"
[11] "film_category" "film_list"
[13] "film_text" "inventory"
[15] "language" "nicer_but_slower_film_list"
[17] "payment" "rental"
[19] "sales_by_film_category" "sales_by_store"
[21] "staff" "staff_list"
[23] "store"
Querying the Tables
We can query the database tables in MySql using the
function dbSendQuery(). The query gets executed in MySql and the result set is
returned using the R fetch() function. Finally it is stored as a data frame in R.
# Query the "actor" tables to get all the rows.
result = dbSendQuery(mysqlconnection, "select * from actor")

# Store the result in a R data frame object. n = 5 is used to fetch first 5 rows.
data.frame = fetch(result, n = 5)
print(data.fame)
When we execute the above code, it produces the following result −

actor_id first_name last_name last_update


1 1 PENELOPE GUINESS 2006-02-15 04:34:33
2 2 NICK WAHLBERG 2006-02-15 04:34:33
3 3 ED CHASE 2006-02-15 04:34:33
4 4 JENNIFER DAVIS 2006-02-15 04:34:33
5 5 JOHNNY LOLLOBRIGIDA 2006-02-15 04:34:33

Updating Rows in the Tables


We can update the rows in a Mysql table by passing the update query to the
dbSendQuery() function.
dbSendQuery(mysqlconnection, "update mtcars set disp = 168.5 where hp = 110")

Inserting Data into the Tables


dbSendQuery(mysqlconnection, "insert into mtcars(row_names, mpg, cyl,
disp, hp, drat, wt, qsec, vs, am, gear, carb) values('New Mazda RX4 Wag', 21, 6,
168.5, 110, 3.9, 2.875, 17.02, 0, 1, 4, 4)")
After executing the above code we can see the row inserted into the table in the
MySql Environment.

Creating Tables in MySql


We can create tables in the MySql using the function dbWriteTable(). It
overwrites the table if it already exists and takes a data frame as input.
# Create the connection object to the database where we want to create the table.
mysqlconnection = dbConnect(MySQL(), user = 'root', password = '', dbname = 'sakila',
host = 'localhost')

# Use the R data frame "mtcars" to create the table in MySql.


# All the rows of mtcars are taken inot MySql.
dbWriteTable(mysqlconnection, "mtcars", mtcars[, ], overwrite = TRUE)

Dropping Tables in MySql


We can drop the tables in MySql database passing the drop table statement
into the dbSendQuery() in the same way we used it for querying data from tables.
dbSendQuery(mysqlconnection, 'drop table if exists mtcars')

RESULT

Thus accessing a relational data base using PHP, Python and R using mySql
was done successfully
Ex.no. 3a
Creating XML Documents, Document type Definition and XML
Schema
Aim

To create XML Documents, Document type Definition and XML Schema

XML - DTD
The XML Document Type Declaration, commonly known as DTD, is a way to
describe XML language precisely. DTDs check vocabulary and validity of the
structure of XML documents against grammatical rules of appropriate XML
language.

Internal DTD
A DTD is referred to as an internal DTD if elements are declared within the
XML files. To refer it as internal DTD, standalone attribute in XML declaration must
be set to yes. This means, the declaration works independent of an external source.
<?xml version = "1.0" encoding = "UTF-8" standalone = "yes" ?>
<!DOCTYPE address [
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>]>

<address>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</address>
Start Declaration − Begin the XML declaration with the following statement.
<?xml version = "1.0" encoding = "UTF-8" standalone = "yes" ?>

External DTD
In external DTD elements are declared outside the XML file. They are
accessed by specifying the system attributes which may be either the legal .dtd file or
a valid URL. To refer it as external DTD, standalone attribute in the XML declaration
must be set as no. This means, declaration includes information from the external
source.

<?xml version = "1.0" encoding = "UTF-8" standalone = "no" ?>


<!DOCTYPE address SYSTEM "address.dtd">
<address>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</address>
XML - Schemas
XML Schema is commonly known as XML Schema Definition (XSD). It is
used to describe and validate the structure and the content of XML data. XML schema
defines the elements, attributes and data types. Schema element supports Namespaces.
It is similar to a database schema that describes the data in a database.

<?xml version = "1.0" encoding = "UTF-8"?>


<xs:schema xmlns:xs = "http://www.w3.org/2001/XMLSchema">
<xs:element name = "contact">
<xs:complexType>
<xs:sequence>
<xs:element name = "name" type = "xs:string" />
<xs:element name = "company" type = "xs:string" />
<xs:element name = "phone" type = "xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

Definition Types
You can define XML schema elements in the following ways
Simple Type
Simple type element is used only in the context of the text. Some of the
predefined simple types are: xs:integer, xs:boolean, xs:string, xs:date. For example −
<xs:element name = "phone_number" type = "xs:int" />

Complex Type
A complex type is a container for other element definitions. This allows you to
specify which child elements an element can contain and to provide some structure
within your XML documents. For example −
<xs:element name = "Address">
<xs:complexType>
<xs:sequence>
<xs:element name = "name" type = "xs:string" />
<xs:element name = "company" type = "xs:string" />
<xs:element name = "phone" type = "xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
Global Types
With the global type, you can define a single type in your document, which
can be used by all other references. For example, suppose you want to generalize
the person and company for different addresses of the company. In such case, you can
define a general type as follows −
<xs:element name = "AddressType">
<xs:complexType>
<xs:sequence>
<xs:element name = "name" type = "xs:string" />
<xs:element name = "company" type = "xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>

RESULT

Ex.no. 3b
XML Queries

Thus Creating XML Documents, Document type Definition and XML Schema
using mySql was done successfully
Aim

To create XML queries using SQL

XQuery
XQuery is About Querying XML. XQuery is a language for finding and
extracting elements and attributes from XML documents.

 XQuery is the language for querying XML data


 XQuery for XML is like SQL for databases
 XQuery is built on XPath expressions
 XQuery is supported by all major databases
 XQuery is a W3C Recommendation

XQuery Example
for $x in doc("books.xml")/bookstore/book
where $x/price>30
order by $x/title
return $x/title

XQuery and XPath

XQuery 1.0 and XPath 2.0 share the same data model and support the same
functions and operators. If you have already studied XPath you will have no problems
with understanding XQuery.

XML Example Document


We will use the following XML document in the examples below.

"books.xml":

<?xml version="1.0" encoding="UTF-8"?>

<bookstore>

<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>

<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>

<book category="WEB">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>

<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>

</bookstore>

The doc() function is used to open the "books.xml" file:

doc("books.xml")

path expression is used to select all the title elements in the "books.xml" file:

doc("books.xml")/bookstore/book/title

XQuery above will extract the following:

<title lang="en">Everyday Italian</title>


<title lang="en">Harry Potter</title>
<title lang="en">XQuery Kick Start</title>
<title lang="en">Learning XML</title>

XQuery above will extract the following:

<title lang="en">Everyday Italian</title>


<title lang="en">Harry Potter</title>
<title lang="en">XQuery Kick Start</title>
<title lang="en">Learning XML</title>
Add HTML Elements

we want to add some HTML elements to the result. We will put the result in
an HTML list - together with some text:

<html>
<body>

<h1>Bookstore</h1>

<ul>
{
for $x in doc("books.xml")/bookstore/book
order by $x/title
return <li>{data($x/title)}. Category: {data($x/@category)}</li>
}
</ul>

</body>
</html>

The XQuery expression above will generate the following result:

<html>
<body>

<h1>Bookstore</h1>

<ul>
<li>Everyday Italian. Category: COOKING</li>
<li>Harry Potter. Category: CHILDREN</li>
<li>Learning XML. Category: WEB</li>
<li>XQuery Kick Start. Category: WEB</li>
</ul>

</body>
</html>

Selecting and Filtering Elements

we are selecting and filtering elements with either a Path expression or with a
FLWOR expression.

Look at the following FLWOR expression:

 for - (optional) binds a variable to each item returned by the in expression


 let - (optional)
 where - (optional) specifies a criteria
 order by - (optional) specifies the sort-order of the result
 return - specifies what to return in the result
for $x in doc("books.xml")/bookstore/book
where $x/price>30
order by $x/title
return $x/title

The for Clause

The for clause binds a variable to each item returned by the in expression. The for
clause results in iteration. There can be multiple for clauses in the same FLWOR
expression.

To loop a specific number of times in a for clause, you may use the to keyword:

for $x in (1 to 5)
return <test>{$x}</test>

Output:

<test>1</test>
<test>2</test>
<test>3</test>
<test>4</test>
<test>5</test>

The at keyword can be used to count the iteration:

for $x at $i in doc("books.xml")/bookstore/book/title
return <book>{$i}. {data($x)}</book>

Output:

<book>1. Everyday Italian</book>


<book>2. Harry Potter</book>
<book>3. XQuery Kick Start</book>
<book>4. Learning XML</book>

It is also allowed with more than one in expression in the for clause. Use comma to
separate each in expression:

for $x in (10,20), $y in (100,200)


return <test>x={$x} and y={$y}</test>

Output:
<test>x=10 and y=100</test>
<test>x=10 and y=200</test>
<test>x=20 and y=100</test>
<test>x=20 and y=200</test>

RESULT

Thus creating XML Queries like adding selecting text to a table using SQL
commands was done successfully
Ex.no. 4a
Creating Database using MongoDB

Aim
To create a database using MongoDB

MongoDB - Create Database

The use Command


MongoDB use DATABASE_NAME is used to create database. The
command will create a new database if it doesn't exist, otherwise it will return the
existing database.
a database with name <mydb>, then use DATABASE statement would be as follows
>use mydb
switched to db mydb
To check currently selected database, use the command db
>db
mydb
check your databases list, use the command show dbs.
>show dbs
local 0.78125GB
test 0.23012GB
created database (mydb) is not present in list. To display database, you need to insert
at least one document into it.
>db.movie.insert({"name":"tutorials point"})
>show dbs
local 0.78125GB
mydb 0.23012GB
test 0.23012GB

The dropDatabase() Method


MongoDB db.dropDatabase() command is used to drop a existing database.
Syntax
Basic syntax of dropDatabase() command is as follows −
db.dropDatabase()
This will delete the selected database. If you have not selected any database,
then it will delete default 'test' database.
First, check the list of available databases by using the command, show dbs.
>show dbs
local 0.78125GB
mydb 0.23012GB
test 0.23012GB
>
If you want to delete new database <mydb>, then dropDatabase() command would
be as follows −
>use mydb
switched to db mydb
>db.dropDatabase()
>{ "dropped" : "mydb", "ok" : 1 }
>
Now check list of databases.
>show dbs
local 0.78125GB
test 0.23012GB
>

The createCollection() Method


MongoDB db.createCollection(name, options) is used to create collection.
>use test
switched to db test
>db.createCollection("mycollection")
{ "ok" : 1 }
>
You can check the created collection by using the command show collections.
>show collections
mycollection
system.indexes
MongoDB, you don't need to create collection. MongoDB creates collection
automatically, when you insert some document.
>db.tutorialspoint.insert({"name" : "tutorialspoint"}),
WriteResult({ "nInserted" : 1 })
>show collections
mycol
mycollection
system.indexes
tutorialspoint
>

The drop() Method


MongoDB's db.collection.drop() is used to drop a collection from the
database.
Example
First, check the available collections into your database mydb.
>use mydb
switched to db mydb
>show collections
mycol
mycollection
system.indexes
tutorialspoint
>
Now drop the collection with the name mycollection.
>db.mycollection.drop()
true
>
Again check the list of collections into database.
>show collections
mycol
system.indexes
tutorialspoint
>
drop() method will return true, if the selected collection is dropped successfully,
otherwise it will return false.

RESULT

Ex.no. 4b
Creating Database using DynamoDB

Thus creating Databases using MongoDB was done successfully


Aim
To create a database using DynamoDB

DynamoDB – Create Table


Tables are the backbone of any Relational Database Management System.
Tables are used to store data in an organized form so operation on the data and retrieval
of data becomes seamless. The AWS DynamoDB provides both RDBMS and Non-
relational databases.

Step by step process


Step 1: Sign in to the AWS Management Console and open the DynamoDB console.

Step 2: In the navigation pane on the left side of the console, choose Dashboard.
Step 3: On the right side of the console, choose Create Table.

Step 4: Fill in the table details as depicted below:

Step 5: After filling in the details click on Create:


At this point your table is ready and you can start adding data into it.

RESULT

Thus creating Databases using DynamoDB was done through step by step
process successfully
Ex.no. 5
Implementing Access control in Relational Databases

Aim
To Implement Access control in Relational Databases

RELATIONAL DATABASES
A relational database stores data in relations which are expected to satisfy
some simple mathematical properties. Roughly speaking, a relation can be thought of
as a table, and is often shown as such. The columns of the table are called attributes
and the rows are called tuples

The relation instance gives us the tuples of the relation at a given instant. For
example, consider the following relation scheme for the EMPLOYEE relation

EMPLOYEE(NAME, DEPT, RANK, OFFICE, SALARY, SUPERVISOR)

Let the domain of the NAME, DEPT, RANK, OFFICE, and SUPERVISOR
attributes be character strings, and the domain of the SALARY attribute be integers.

The CREATE Statement Consider the EMPLOYEE relation discussed earlier.


The relation scheme is defined in SQL by the following command.

CREATE TABLE EMPLOYEE ( NAME CHARACTER NOT NULL, DEPT


CHARACTER, RANK CHARACTER, OFFICE CHARACTER, SALARY
INTEGER, SUPERVISOR CHARACTER, PRIMARY KEY (NAME), FOREIGN
KEY (DEPT) REFERENCES DEPARTMENT, FOREIGN KEY (SUPERVISOR)
REFERENCES EMPLOYEE )

INSERT Statements
The EMPLOYEE table is initially empty.

Tuples are inserted into it by means of the SQL INSERT statement


INSERT INTO EMPLOYEE(NAME, DEPT, RANK, OFFICE, SALARY,
SUPERVISOR)

VALUES(`Black, `Administration', `Dean', `ST101', 60000, NULL)

The SELECT Statement


Retrieval of data is effected in SQL by the SELECT statement. For example, the
NAME, SALARY and SUPERVISOR data for employees in the Computer Sci department is
extracted as follows.

SELECT NAME, SALARY, SUPERVISOR FROM EMPLOYEE WHERE DEPT =


`Computer Sci'

This query applied to instance of EMPLOYEE given above returns the data shown below

The UPDATE Statement


Finally the UPDATE statement allows one or more attributes of existing
tuples in a relation to be modified. For example, the following statement gives all
employees in the ComputerSci department a raise of $1000.

UPDATE EMPLOYEE SET SALARY = SALARY + 1000 WHERE DEPT =


`Computer Sci'

BASE RELATIONS AND VIEWS

The concept of a view has important security application in relational systems.


A view is a virtual relation which is derived by an SQL definition from base relations
and other views.

For example, consider the EMPLOYEE relation discussed earlier. This is a


base relation. The following SQL statement defines a view called COMPUTER SCI
DEPT.

CREATE VIEW COMPUTER SCI DEPT AS SELECT NAME, SALARY,


SUPERVISOR FROM EMPLOYEE WHERE DEPT = `Computer Sci'

This defines the virtual relation shown below.


To illustrate the dynamic aspect of views suppose that a new employee Turing is
inserted in base relation EMPLOYEE, modifying it as follows.

The view COMPUTER SCI DEPT will be automatically modied to include Turing, as
shown below

MANDATORY ACCESS CONTROLS


Mandatory access controls are based on security labels associated with each
data item and each user. A label on a data item is called a security classification, while
a label on a user is called a security clearance. In a computer system every program
run by a user inherits the user's security clearance.

RESULT
Thus implementing access control in relational database was done successfully

You might also like