0% found this document useful (0 votes)
6 views96 pages

advanced datbase technology lab-final

The document outlines the procedures for performing CRUD operations, indexing, and sharding in MongoDB, as well as similar operations in Cassandra and Hive. It includes prerequisites, installation steps, and detailed command examples for creating databases, collections, and tables, along with data manipulation commands. The document concludes with successful execution results for each database operation performed.

Uploaded by

p.swathipalani96
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)
6 views96 pages

advanced datbase technology lab-final

The document outlines the procedures for performing CRUD operations, indexing, and sharding in MongoDB, as well as similar operations in Cassandra and Hive. It includes prerequisites, installation steps, and detailed command examples for creating databases, collections, and tables, along with data manipulation commands. The document concludes with successful execution results for each database operation performed.

Uploaded by

p.swathipalani96
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/ 96

1

2
3
4

EXP NO: 1a
MongoDB
DATE:
AIM:
To Perform MongoDB CRUD Operations,Indexing and Sharding.
Prerequisites:
Step1:
MongoDB Compass :GUI for MongoDB, MongoDB Compass allows you to make smarter decisions
about document structure, querying, indexing, document validation
MongoDB Compassgui Environment from online
Gotohttps://www.mongodb.com/try/download/compass?tck=docs_compass
Downloade mongodb-compass-1.25.0-win32-x64.exe
Step2:
After Installation , Open MongoDB Compass from the drive installed in our system0
Dv
dV
dv
Dvf
C:\Users\SRIMATHI\AppData\Local\MongoDBCompass

a) Open the theabove mentioned Folder

b) Click connect to option to load plugins needed to load MongoDB


5

c) MongoDB Uses the port number 27017

d) Click the connect option it shows following dialog box:

Step3 :Perform crud Operations using Editor:

1. Creation of Databaaseand Collections:


6

Create database by clicking the create database button


As follows databasesriemp ,collectionsviims

Go to the database sridb and click viims collection to insert record  click add data
7

2. Insertion of Documents:

In the Insert document dialog >> insert field and Value>> Data types.
Type the following fields and click the button insert

Next, we want to add a new Field after the name, click plus icon (+) under the name and follow the above
discussed instructions.
8

3.Deletion of Documentation:
From the Documents tab, click on a document that you want to delete. Then there will appear a small
trash icon from the document tab >> Delete.
9

4.Drop the Collections:


10

5. Drop Database:
11

6. Update Document
Click on the pencil icon which is visible when you choose your document that needs to be modified.
12

7. Read Document:
Click on the “Option” button at Line editor and give a filter query which field you need to search
then hit the “FIND” button
13
14

8. indexing:

================================================
Working with MongoDB Shell:
1) To Create a new database:
>use Bhuvan
'switched to dbBhuvan'
===============================================
2) To Create a collection:
>db.createCollection("MCA1")
Output: { ok: 1 }
=============================================
15

3) Inserting single document into the collection:


>db.VIIMS.insertOne({empno:1,empname:"bhuvana",salary:90000})
Output:
<{ acknowledged: true,insertedId: ObjectId("62c5340cc75aba6b64bf52da") }
4) Inserting Multiple document into the collection:
>db.VIIMS.insertMany([{empno:2,empname:"Sri",salary:60000},{empno:3,empname:"Goki",
salary:80000},{empno:4,empname:"kanch",salary:45000}])
Output:
<{ acknowledged: true, insertedIds: { '0': ObjectId("62c5302bc75aba6b64bf52d7"),
'1': ObjectId("62c5302bc75aba6b64bf52d8"),
'2': ObjectId("62c5302bc75aba6b64bf52d9") } }
===============================================
5) To find the particular database:
>db.VIIMS.find({empno:1})
Output:
<{ _id: ObjectId("62c52db1c75aba6b64bf52d6"),empno: 1,empname: 'bhuvana',
salary: 90000 }
================================================
6)To find all the documents:
>db.VIIMS.find({})
Output:
<{ _id: ObjectId("62c52db1c75aba6b64bf52d6"), empno: 1,empname: 'bhuvana', salary: 90000 }{
_id: ObjectId("62c5302bc75aba6b64bf52d7"), empno: 2, empname: 'Sri', salary: 60000 } { _id:
ObjectId("62c5302bc75aba6b64bf52d8"), empno: 3, empname: 'Goki', salary: 80000 } { _id:
ObjectId("62c5302bc75aba6b64bf52d9"),empno: 4,empname: 'kanch', salary: 45000 }
================================================
7)Query operations:
a. In Operator in find() Method:
>db.VIIMS.find({empname:{$in:["Sri","kanch","Goki"]}})
Output:
<{ _id: ObjectId("62c52db1c75aba6b64bf52d6"), empno: 1, empname: 'bhuvana', salary: 90000 } {
_id: ObjectId("62c5302bc75aba6b64bf52d7"), empno: 2, empname: 'Sri', salary: 60000 } { _id:
16

ObjectId("62c5302bc75aba6b64bf52d8"), empno: 3, empname: 'Goki', salary: 80000 } { _id:


ObjectId("62c5302bc75aba6b64bf52d9"), empno: 4, empname: 'kanch', salary: 45000 }

b. In Operator with AND Condition in find() Method:

>db.VIIMS.find({empname:{$in:["Sribhuvana","Goki","Prema","Sri"]},salary:{$gte:50000}})
Output:
<{ _id: ObjectId("62c5302bc75aba6b64bf52d7"), empno: 2, empname: 'Sri', salary: 60000 }
{ _id: ObjectId("62c5302bc75aba6b64bf52d8"), empno: 3, empname: 'Goki', salary: 80000 }
{ _id: ObjectId("62c5340cc75aba6b64bf52da"), empno: 1, empname:'bhuvana', salary: 90000 }
c. In Operator with OR Condition in find() Method:
>db.VIIMS.find({$or:[{empname:{$in:["goki","bhuvana","s ri"]}},{salary:{$gte:75000}}]})
Output:
<{ _id: ObjectId("62c5302bc75aba6b64bf52d8"), empno: 3, empname: 'Goki', salary: 80000 }
{ _id: ObjectId("62c5340cc75aba6b64bf52da"), empno: 1, empname: 'bhuvana', salary: 90000 }
d. In Operator with simple OR Condition in find() Method:
>db.VIIMS.find({$or:[{empname:"sri"},{salary:{$gte:80000} }]})
Output:
<{ _id: ObjectId("62c5302bc75aba6b64bf52d8"), empno: 3, empname: 'Goki', salary: 80000 }
{ _id: ObjectId("62c5340cc75aba6b64bf52da"), empno: 1, empname: 'bhuvana', salary: 90000 }
=============================================
e) Update Single record in database:
>db.VIIMS.updateOne({empno:4},{$set:{empname:"kanch", salary:45000}})
Output:
<{ acknowledged: true, insertedId: null, matchedCount: 1, modifiedCount: 0, upsertedCount: 0 }
===============================================

f) Update many records in database::


>db.VIIMS.updateMany({salary:{$lte:60000}},{$inc:{salary:500}})
<{ acknowledged: true, insertedId: null, matchedCount: 2, modifiedCount: 2, upsertedCount: 0 }
==============================================
g) Delete Single record in Table:
>db.VIIMS.deleteOne({empno:4})
17

Output:
<{ acknowledged: true, deletedCount: 1 }
g) Delete a particular column in Table:
>db.VIIMS.updateMany({},{$unset:{_salary:" "}})
Output:
>{ acknowledged: true, insertedId: null, matchedCount: 3, modifiedCount: 0, upsertedCount: 0 }
h) Delete entire records in Table:
>db.VIIMS.deleteMany({})
Output:
<{ acknowledged: true, deletedCount: 3 }
=======================================================

Result:
Thus the above program has been successfully completed and executed.

EXP NO: 1b
Cassandra
DATE:

AIM:
To Perform Table Operations,CRUDOperations,CQL Types using Cassandra.
Step1: PREREQUSITES:
Requirement: (Download all the required and install)
18

1. Java8 First Install Java 8


2. Python 2.7 Install Python2.7
3. Cassandra 3.11.10  Install Cassandra
Step2: Configure Environment Variables for Java 8 go to this pc right click and select properties 
go to advanced tab click environment Variables.

Enter JAVA_HOME for the new variable name. Select the Variable value field and then the Browse
Directory option.
19

Navigate to This PC > Local Disk C: > Program Files > Java > jdk1.8.0_251 and select OK.
Once the correct path to the JDK 8 installation folder has been added to the JAVA_HOME system variable,
click OK.

You have successfully added the JAVA_HOME system variable with the correct JDK 8 path to the variable
list. Select OK in the main Environment Variables window to complete the process.
20

1. Install and Configure Python 2.7 on Windows


21

Step 3: Download and Set Up Apache Cassandra Install Cassandra and set up configuration
variable
22

Type CASSANDRA_HOME for Variable name, then for the Variable value column select the location of
the unzipped Apache Cassandra folder.
Based on the previous steps, the location is C:\Cassandra\apache-cassandra-3.11.6. Once you have
confirmed that the location is correct, click OK.

Setp up system path as follows:


23

Step 4: Start Cassandra from Windows CMD as C:\apache-cassandra-3.11.10\bin and type the
following

cassandra

Note: Do not close the current cmd session.


Step 5: Access Cassandra cqlsh from Windows CMD
24

Enter the following command to access the Cassandra cqlsh bash shell:

cqlsh

CRUD OPERATIONS
Step1: Creating Keyspaces:
CREATE KEYSPACE sriviims WITH replication = {'class':'SimpleStrategy', 'replication_factor' : 3};
Step2: view Keyspaces:
cqlsh> describe keyspaces;
tutorialspointsystem_authsystem_distributedsriviims
system_schema system system_traces
Step3: using keyspaces:
cqlsh> use sriviims;
cqlsh:sriviims>
Step4: Creating Table:
cqlsh:sriviims> CREATE TABLE student(sno int PRIMARY KEY,snametext,depttext,mobile int);
Step5:Inserting values into table:
cqlsh:sriviims> insert into student(sno,dept,mobile,sname) values(1,'mca',23232,'srimathi');
cqlsh:sriviims> insert into student(sno,dept,mobile,sname) values(2,'mca',233232,'kavipriya');
Step6:Rrieving values from table:
cqlsh:sriviims> select * from student;
sno | dept | mobile | sname
-----+------+--------+-----------
1 | mca | 23232 | srimathi
2 | mca | 233232 | kavipriya
(2 rows)
Step7: Update values into table:
cqlsh:sriviims> update student set mobile=93456,dept='mba' where sno=1;
cqlsh:sriviims> select * from student;
sno | dept | mobile | sname
-----+------+--------+-----------
1 | mba | 93456 | srimathi
2 | mca | 233232 | kavipriya
25

(2 rows)
Step8:Delete from table;
cqlsh:sriviims> delete from student where sno=2;
cqlsh:sriviims> select * from student;
sno | dept | mobile | sname
-----+------+--------+----------
1 | mba | 93456 | srimathi
(1 rows)
Step9: Creating User defined data type :
i)Type creation:
cqlsh:sriviims> create type if not exists sriviims.myaddress(
... street text, ... doorno text,... pincode text);
ii)Attaching Type to Table:
cqlsh:sriviims>create table person(pid int primary key,pnametext,address list<FROZEN
<myaddress>>);
iii)Inserting values into table using types:
cqlsh:sriviims> insert into person (pid,pname,address) values(1,'srimathi',[{street:'vivekanandha
street',doorno:'F23 staffquarters',pincode:'625307'}]);
iv)Retrieving Values from table:
cqlsh:sriviims> select * from person;
pid | address | pname
-----+-----------------------------------------------------------------------------------+----------
1 | [{street: 'vivekanandha street', doorno: 'F23 staffquarters', pincode: '625307'}] | srimathi
(1 rows)
v)Creating ,altering and renaming the User Defined Datatypes:
i) Creation of User Defined Datatype:
cqlsh:sri> create type myaddress(street text,district text);
===================================================
ii) View the Datatype:
cqlsh:sri> describe types;
myaddress
==================================================
iii)Altering the Datatype:
26

cqlsh:sri> alter type myaddress ADD pcode int;


cqlsh:sri> describe type myaddress;
================================================
CREATE TYPE sri.myaddress ( street text, district text, pcode int );
---------------------------------------------------------------------------------------------------------
iv)Rename the column in user defined data type:
cqlsh:sri> alter type sri.myaddress rename district to dist;
cqlsh:sri> describe type myaddress;
CREATE TYPE sri.myaddress (
street text, dist text,
pcode int
);
=========================================================

Result:
Thus the above program has been successfully completed and executed

EXP NO: 1C Hive


27

DATE:
AIM:
To Perform Database Operations,partitioning and HiveQL Using Hive.
step1: Prerequisites:
Java
Hadoop
Hive
Derby server
Step2: Check out the path of java and hadoop
C:\Users\SRIMATHI>echo %JAVA_HOME%
C:\java\jdk1.8.0_251
C:\Users\SRIMATHI>D:
D:\>CD %HADOOP_HOME%

D:\hadoop\hadoop-2.8.0>cd D:\hadoop\hadoop-2.8.0\etc\hadoop
D:\hadoop\hadoop-2.8.0\etc\hadoop>hadoop-env.cmd
D:\hadoop\hadoop-2.8.0\etc\hadoop>hdfs namenode –format
28

Go to sbin
D:\hadoop\hadoop-2.8.0\etc\hadoop>cd ..
D:\hadoop\hadoop-2.8.0\etc>cd..
D:\hadoop\hadoop-2.8.0>cd sbin
D:\hadoop\hadoop-2.8.0\sbin>start-dfs
29

Then type the browser to


it can be verified via browser also as –

 Namenode (hdfs) - http://localhost:50070


 Datanode - http://localhost:50075
 All Applications (cluster) - http://localhost:8088 etc.
30

Hadoop datanode

http://localhost:50075/datanode.html

start derby server:


D:\derby\db-derby-10.12.1.1-bin\bin>
D:\derby\db-derby-10.12.1.1-bin\bin>startNetworkServer -h 0.0.0.0

Start the hive server:


Go to another command prompt and type the following
C:\WINDOWS\system32>cd D:\Hive\apache-hive-2.1.0-bin\bin
C:\WINDOWS\system32>d:
[1] Type “jps -m” to check NetworkServerControl
D:\hive\apache-hive-2.1.0-bin\bin>jps -m
74064 DataNode
75860 Jps -m
31

75940 NetworkServerControl start -h 0.0.0.0


71608 NameNode

D:\hive\apache-hive-2.1.0-bin\bin>

[2] Type “hive” to execute hive server.


32

Creating database in hive


hive> create database if not exists sriviims;
Output:
OK
No rows affected (107.734 seconds)
Use the database Created:
hive> use sriviims;
Output:
OK
No rows affected (3.533 seconds)
View the Database Created:
hive> show databases;
Output:
OK
default
sriviims
2 rows selected (13.98 seconds)
Creating table in hive:
create table if not exists student(id BIGINT COMMENT 'viimsstudentid',sname STRING COMMENT
'student name',age INT COMMENT 'age of studnet',fee DOUBLE COMMENT 'college fee',city STRING
COMMENT 'students residing city',address STRING COMMENT 'street with zipcode' ) ;
Output:
OK
No rows affected (13.414 seconds)
To view the tables created in Databases:
hive> SHOW TABLES;
+

Output:
33

DESCRIBING TABLE:
hive> DESCRIBE STUDENT

Output:

..>;
OK
id bigint unique id for each student
name string student name
age int student age
fee double college fee
city string cities to which studentss belongs
state string student home address state
zip string student address zip code
7 rows selected (3.785 seconds)
Creation of table in hive :
Table name: sristudent

hive> create table IF NOT EXISTS sristudent(sid BIGINT COMMENT 'STUDENT ROLL NO',sname
STRING COMMENT 'STUDENT NAME',age INT COMMENT 'COMPLETED AGE',
. . > fee DOUBLE COMMENT 'COLLEGE FEE',address STRING COMMENT 'ADDRESS WITH
PINCODE')
. . > ROW FORMAT DELIMITED
. . > FIELDS TERMINATED BY '|'
. . > LINES TERMINATED BY'\n'
34

. . > STORED AS TEXTFILE;


Output:
OK
No rows affected (73.569 seconds)
===========================================================================
To view the tables Created:
hive> show tables;
Output:
OK
sristudent
student
2 rows selected (4.391 seconds)
===========================================================
Discribe the table created:
hive> describe sristudent;
Output:
OK
sidbigint STUDENT ROLL NO
snamestring STUDENT NAME
age int COMPLETED AGE
fee double COLLEGE FEE
address string ADDRESS WITH PINCODE
5 rows selected (4.648 seconds)
===========================================================
LOAD Command for Inserting Data Into Hive Tables
Create a sample text file using ‘|’ delimiter – under D:/hive/mcaviimsstudent.txt

hive>
hive> load data local inpath 'D:/hive/mcaviimsstudent.txt' overwrite into table sristudent;
Output:
Loading data to table sriviims.sristudent
OK
No rows affected (114.297 seconds)
Retrieving data from table:
35

Partiioning creation in hive:


hive> create table sripartition(id int,namestring,ageint,isntitute string)
. . > partitioned by(course string)
. . > row format delimited
. . > fields terminated by ',';
Output:OK
No rows affected (19.441 seconds)
To view the partition Created:
hive> describe sripartition;
Output:

Create student_details.txt in d:/hive/ folder


36

Load data in the table and pass the values of partition columns with I by using the following
command:
hive> load data localinpath 'd:/hive/student_details.txt' into table sripartition . . > partition(course="mca");
Output:
Loading data to table sriviims.sripartition partition (course=mca)
OK
No rows affected (110.093 seconds)
Retrieving the data from partitioned table:
hive> select * from sripartition;
Output:
10:54:00.585 [f54ea8fb-7da9-40bd-9697-48c43d1dc6f2 main] ERROR
org.apache.hadoop.hdfs.KeyProviderCache - Could not find uri with key
[hadoop.security.key.provider.path] to create a keyProvider !!
OK
name institutemca
1 srimathi 35 viimsmca
2 kavipriya 22 viimsmca
3 chithra 23 viimsmca
4 hemasri 24 viimsmca
5 nisha 23 viimsmca
6 gayathri 22 viimsmca
7 anitha 35 viimsmca
8 rows selected (281.941 seconds)

To view the partitions created in Browser through utilities tab:


 Go to browser name node  http:localhost/50070
 Goto utilities tab
37

 Type the following command in browser


 /user/hive/warehouse/sriviims.db/sripartition
 Click ok
The following screenshshot,shows that tale student is divided based on course=’mca’

The following dialogue box shows the partition values based on course :

hive> select * from sripartition where course="mca";


Output:
OK
name institutemca
1 srimathi 35 viimsmca
2 kavipriya 22 viimsmca
3 chithra 23 viimsmca
4 hemasri 24 viimsmca
5 nisha 23 viimsmca
6 gayathri 22 viimsmca
7 anitha 35 viimsmca
8 rows selected (73.322 seconds)
38

Hiveql:
Built-in operators
Group by operator:
1.create table emp;
2.create file text file named myemp.txt
hive> create table myemp(id bigint,namestring,ageint,addressstring,salarydouble,dept string)
. . > row format delimited
. . > fields terminated by '|'
. . > lines terminated by '\n'
. . > stored as textfile;
OK
No rows affected (169.323 seconds)
hive> load data local inpath 'd:/hive/emp.txt' into table myemp;
Loading data to table sriviims.myemp
OK
No rows affected (99.835 seconds)

========================================================

Result:
Thus the above program has been successfully completed and executed.
39

EXP NO:1D
OrientDB
DATE:
AIM:
To PerformOrientDB Graph Database creation and Perform Operations.
http://localhost:2480/studio/index.html#/database/sridb/browse
Step 1 − Download OrientDB Binary Setup File orientdb-tp3-3.1.9.tar
Step 2 − Extract and Install OrientDB
 Extract the zip file using the zip extractor.
 Move the extracted folder into the C:\ directory.
Step3 – Create Environmental variables:
Create two environmental variables ORIENTDB_HOME and PATH variables with
following given values.
ORIENT_HOME = C:\orientdb-community-2.1.9
PATH = C:\orientdb-community-2.1.9\bin
Step 4 − Configuring OrientDB Server as a Service
Use Apache Common Daemon which allow Windows users to wrap Java applications as Windows
service.
 Click on common-daemon-1.0.15-bin-windows to download.
 Unzip the common-daemon-1.0.15-bin-windows directory. After extracting you will
find prunsrv.exe and prunmgr.exe files inside the directory. In those −
o prunsrv.exe file is a service application for running applications as services.
o prunmgr.exe file is an application used for monitoring and configuring windows services.
 Go to OrientDB installation folder → create a new directory and name it service.
 Copy the prunsrv.exe and prunmgr .exe paste it into to the service directory.
 you have to rename prunsrv and prunmgr according to the name of the service. For
e.g.OrientDBGraph and OrientDBGraphw respectively
Copy the following scriptinto the file named installService.bat and place it
into %ORIENTDB_HOME%\service\ directory.
===========================================================
::OrientDB Windows Service Installation
@echo off
rem Remove surrounding quotes from the first parameter
set str=%~1
rem Check JVM DLL location parameter
if "%str%" == "" gotomissingJVM
set JVM_DLL=%str%
rem Remove surrounding quotes from the second parameter
set str=%~2
rem Check OrientDB Home location parameter
if "%str%" == "" gotomissingOrientDBHome
40

set ORIENTDB_HOME=%str%
set CONFIG_FILE=%ORIENTDB_HOME%/config/orientdb-server-config.xml
set LOG_FILE = %ORIENTDB_HOME%/config/orientdb-server-log.properties
set LOG_CONSOLE_LEVEL = info
set LOG_FILE_LEVEL = fine
set WWW_PATH = %ORIENTDB_HOME%/www
set ORIENTDB_ENCODING = UTF8
set ORIENTDB_SETTINGS = -Dprofiler.enabled = true
-Dcache.level1.enabled = false Dcache.level2.strategy = 1
set JAVA_OPTS_SCRIPT = -XX:+HeapDumpOnOutOfMemoryError
rem Install service
OrientDBGraphX.X.X.exe //IS --DisplayName="OrientDBGraphEd X.X.X" ^
--Description = "OrientDB Graph Edition, aka GraphEd, contains OrientDB server
integrated with the latest release of the TinkerPopOpen Source technology
stack supporting property graph data model." ^
--StartClass = com.orientechnologies.orient.server.OServerMain
-StopClass = com.orientechnologies.orient.server.OServerShutdownMain ^

--Classpath = "%ORIENTDB_HOME%\lib\*" --JvmOptions


"Dfile.Encoding = %ORIENTDB_ENCODING%; Djava.util.logging.config.file = "%LOG_FILE%";
Dorientdb.config.file = "%CONFIG_FILE%"; -Dorientdb.www.path = "%WWW_PATH%";
Dlog.console.level = %LOG_CONSOLE_LEVEL%; -Dlog.file.level = %LOG_FILE_LEVEL%;
Dorientdb.build.number = "@BUILD@"; -DORIENTDB_HOME = %ORIENTDB_HOME%" ^

--StartMode = jvm --StartPath = "%ORIENTDB_HOME%\bin" --StopMode = jvm


-StopPath = "%ORIENTDB_HOME%\bin" --Jvm = "%JVM_DLL%"
-LogPath = "%ORIENTDB_HOME%\log" --Startup = auto

EXIT /B

:missingJVM
echo Insert the JVM DLL location
gotoprintUsage

:missingOrientDBHome
echo Insert the OrientDB Home
gotoprintUsage

:printUsage
echo usage:
echo installServiceJVM_DLL_locationOrientDB_Home
EXIT /B

The script requires two parameters −


 The location of jvm.dll, for e.g. C:\ProgramFiles\java\jdk1.8.0_66\jre\bin\server\jvm.dll
 The location of OrientDB installation for e.g.C:\orientdb-community-2.1.9
41

 The service is installed when you execute the OrientDBGraph.exe file (Original prunsrv) and
double-click on it.
 Use the following command to install services into Windows.
> Cd %ORIENTDB_HOME%\service
> installService.bat "C:\Program Files\Java\jdk1.8.0_66\jre\bin\server
\jvm.dll" C:\orientdb-community-2.1.9
Open the Task Manager services, you will find the following screenshot with the registered service name is
in it.

Step5: Verifying OrientDB Installation


This step verifies the OrientDB database server installation using the following steps.
 Run the server.
Start the server with start the server with
server.bat
Run the console.
server.bash file
42

Password: root user


Double click the console batch file

http://localhost:2480/studio/index.html#/

Creation of new database:


Click the new database button and give user name as root and password as root user
43

1. Consider a graph database that maps the relationship between individual users and their cars.
2. First, create the graph schema for the Person and Car vertex classes, as well as the Owns edge class
to connect the two:

https://orientdb.com/docs/3.0.x/gettingstarted/Tutorial-Using-schema-with-graphs.html
44
45

create a vertex class for the country, in which the person lives and an edge class that connects the
individual to the place.

3. The vertex class Country recording countries in which people live and the edge class Lives to
connect individuals in the vertex class Person to entries in Country.
With the schema laid out, create a vertex for the United Kingdom and connect it to the person Luca.
46
47

Output:

Result:
Thus the above program has been successfully completed and executed.
48

EXP NO:2
MYSQL DATABASES
DATE:
Aim:
To perform mysql database creation ,Table Creation and Quering in mysql databases
Prerequisites:
Download mysql-installer-community-8.0.23.0.msi from
websitehttps://dev.mysql.com/downloads/file/?id=501541
Password: srimathi

Open mysql workbench


Give password as srimathi
========================================================
Creating database in mysql:
create database sriviims;
Output:
13:48:40 create database sriviims 1 row(s) affected 0.219 sec
To view the databases created in mysql:
show databases;

Output:

information_schema
Mysql
performance_schema
Sakila
Sriviims
Sys
World
select * from viimstudents;
Creating tables in Mysql:
use sriviims;
create table student(sid int primary key,sname varchar(20),dob date);
Output:
Field Type Null Key Default Extra
Sid Int NO PRI
Sname varchar(20) YES
Dob date YES
49

Insert ing values in to tables:

insert into student values(1,'srimathi','1981-10-10');


insert into student values(2,'hemasri','1991-05-05');
insert into student values(3,'Gayathri','1995-04-05');
insert into student values(4,'Rithigha','1999-06-08');
===========================================================
Retriving values from tables:
select * from student;
1 Srimathi 1981-10-10
2 Hemasri 1991-05-05
3 Gayathri 1995-04-05
4 Rithigha 1999-06-08

Loading data into mysql:


Keep student.txt in folder as “'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/student.txt'”

mysql> insert
-> into table student
-> fields terminated by '\t'
-> LINES TERMINATED BY '\n'
-> ignore 1 rows;
Query OK, 2 rows affected (0.85 sec)
Records: 2 Deleted: 0 Skipped: 0 Warnings: 0
======================================================
Drop the table:
mysql> drop table emp;
Output:
Query OK, 0 rows affected (2.37 sec)
Create the table:
create table emp(enoint,ename varchar(10),sal double);
Query OK, 0 rows affected (1.59 sec)
Loading the file into table:
Create emp.csv file under folder as 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/emp.csv’
50

========================================================
mysql> load data infile 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/emp.csv'
-> into table emp
-> fields terminated by ','
-> enclosed by '"'
-> lines terminated by '\r\n'
-> ignore 1 rows;
Query OK, 4 rows affected (0.19 sec)

Output:

DELETETING THE RECORDS FROM TABLE:


mysql> delete from student where sidin(6,7);
OUTPUT:
Query OK, 2 rows affected (0.32 sec)

SELECT QUERY:
a) Using where clause:
mysql> select * from emp where ename='srimathi';
+------+----------+------+
| eno |ename | sal |
+------+----------+------+
| 2 | Srimathi | 4000 |
+------+----------+------+
51

1 row in set (0.00 sec)

b)Using like Operator


mysql> select * from emp where ename like '%thi';
Output:
+------+------------+------+
| eno |ename | sal |
+------+------------+------+
| 2 | Srimathi | 4000 |
| 5 | valarmathi | 6000 |
+------+------------+------+
2 rows in set (0.00 sec)

c) Order by Clause:
mysql> select * from emp order by ename;
Output:
+------+------------+------+
| eno |ename | sal |
+------+------------+------+
| 4 | Aradhana | 8000 |
| 1 | Hemasri | 5000 |
| 2 | Srimathi | 4000 |
| 5 | valarmathi | 6000 |
| 3 | Vishnu | 6000 |
+------+------------+------+
5 rows in set (0.02 sec)

mysql> select * from emp order by sal desc;

Output:
+------+------------+------+
| eno |ename | sal |
+------+------------+------+
| 4 | Aradhana | 8000 |
| 3 | Vishnu | 6000 |
52

| 5 | valarmathi | 6000 |
| 1 | Hemasri | 5000 |
| 2 | Srimathi | 4000 |
+------+------------+------+
5 rows in set (0.01 sec)

d) SQL Having clause:


mysql> select count(eno),deptno from emp group by deptno having deptno in(10,20);
+------------+--------+
| count(eno) | deptno |
+------------+--------+
| 3 | 10 |
| 2 | 20 |
+------------+--------+
2 rows in set (0.00 sec)
e) SQL exists clause:
mysql> select deptno, dname from dept where exists(select deptno from emp where
emp.deptno=dept.deptno);
+--------+-------+
| deptno | dname |
+--------+-------+
| 10 | Admin |
| 20 | IT |
| 30 | HR |
+--------+-------+
3 rows in set (0.00 sec)
53

f) any Operator:
The ANY operator returns TRUE if any of the subquery values meet the condition.
mysql> select dname from dept where deptno=any(select deptno from emp where deptno in(10,30));
Output:
+-------+
| dname |
+-------+
| Admin |
| HR |
+-------+
2 rows in set (0.04 sec)
G ) all Operator:
The ALL operator returns TRUE if all of the subquery values meet the condition.
The following SQL statement returns TRUE and lists the department number if ALL the records in the dept
table has deptno=10(so, this example will return FALSE, because not ALL records in the dept table has
deptno = 10):

mysql> select ename from emp where deptno =all(select deptno from dept where deptno=10);
Output:
+------------+
| ename |
+------------+
| Hemasri |
| Vishnu |
| valarmathi |
+------------+
3 rows in set (0.00 sec)
h. Case Statement:
The CASE statement goes through conditions and returns a value when the first condition is met (like an IF-
THEN-ELSE statement). So, once a condition is true, it will stop reading and return the result. If no
conditions are true, it returns the value in the ELSE clause.

mysql> select ename,sal,


-> case
54

-> when sal>=6000 then 'your Salary is greater than 6000'


-> when sal<6000 then 'Your salary is less than 6000'
-> else 'salary is higher'
-> end as salary_report
-> from emp;
Output:
+------------+------+----------------------------------+
| ename | sal |salary_report |
+------------+------+----------------------------------+
| Hemasri | 5000 | Your salary is less than 6000 |
| Srimathi | 4000 | Your salary is less than 6000 |
| Vishnu | 6000 | your Salary is greater than 6000 |
| Aradhana | 8000 | your Salary is greater than 6000 |
| valarmathi | 6000 | your Salary is greater than 6000 |
| Banumathi | 6000 | your Salary is greater than 6000 |
| Chithra | 8000 | your Salary is greater than 6000 |
+------------+------+----------------------------------+
7 rows in set (0.00 sec)

Alter table:
Add column:
mysql> alter table emp add column(dept int);
Modify Column:
mysql> alter table emp RENAME COLUMN dept to deptno;

Output:
Query OK, 0 rows affected (1.24 sec)
Records: 0 Duplicates: 0 Warnings: 0
55

Updating the table:


With Set Keyword:
mysql> select * from emp;
Output:
+------+------------+------+------+
| eno |ename | sal | dept |
+------+------------+------+------+
| 1 | Hemasri | 5000 | NULL |
| 2 | Srimathi | 4000 | NULL |
| 3 | Vishnu | 6000 | NULL |
| 4 | Aradhana | 8000 | NULL |
| 5 | valarmathi | 6000 | NULL |
+------+------------+------+------+
5 rows in set (0.00 sec)
========================================================

mysql> update emp set dept=10 where eno=1;


Output:
Query OK, 1 row affected (0.12 sec)
Rows matched: 1 Changed: 1 Warnings: 0
========================================================

mysql> set @deptid:=20;


Query OK, 0 rows affected (0.00 sec)
=======================================================
mysql> update emp set dept=@deptid where eno=2;
Query OK, 1 row affected (0.12 sec)
Rows matched: 1 Changed: 1 Warnings: 0

mysql> update emp set dept=@deptid wheereeno=4;


ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near 'wheereeno=4' at line 1
mysql> update emp set dept=@deptid where eno=4;
Query OK, 1 row affected (0.10 sec)
Rows matched: 1 Changed: 1 Warnings: 0
56

/
Join query:
Create another table dept with dept, deptname;

Inner join:
 INNER JOIN that selects records that have matching values in both tables:
select ename,emp.deptno,dept.dname from emp inner join dept on emp.deptno=dept.deptno;
 LEFT (OUTER) JOIN: Returns all records from the left table, and the matched records from the
right table
mysql> select eno,dname from dept left outer join emp on dept.deptno=emp.deptno;
 RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched records from the
left table
select emp.deptno,dname from dept right outer join emp on dept.deptno=emp.deptno;
 FULL (OUTER) JOIN: Returns all records when there is a match in either left or right table

Output:

Inner join :
57

Left outer join:

Right outer Join:


58

Result:

Thus the above program has been successfully completed and executed.
59

EXP NO:3
MYSQL REPLICATION
DATE:

Aim:
To perform MYSQL Replication Distributed Databaase.
Prerequisites:

Step1Download WampServer_(64bit)_v3.1.9.exe file and install wamp server in windows.


Step2 run all the service

Step3click phpmyadim
Step4 give username as root and password as empty
Step5 click replication tab

Step6 click master and click configure


Result:
Thus the above program has been successfully completed and executed.
60

EXP NO: 4
SPATIAL DATA STORAGE AND RETRIEVAL IN MYSQL
DATE:

Aim:
To perform Spatial Data storage and retrieval in Mysql.
Prerequisites:

Install mysql-installer-community-8.0.23.0 or mysql workbench


Basics about Spatial Data storage:
Data types:
Spatial data types hold single geometry values:
 GEOMETRY
 POINT
 LINESTRING
 POLYGON

Spatial data types hold collections of values:


 MULTIPOINT
 MULTILINESTRING
 MULTIPOLYGON
 GEOMETRYCOLLECTION

GEOMETRYCOLLECTION:
GEOMETRYCOLLECTION can store a collection of objects of any type. The other collection types
(MULTIPOINT, MULTILINESTRING, and MULTIPOLYGON) restrict collection members to those
having a particular geometry type.
Spatial data formats MySQL uses:
 Well-Known Text (WKT) Format
 Well-Known Binary (WKB) Format
 Internal Geometry Storage Format

The Well-Known Text (WKT) representation of geometry values is designed for exchanging geometry data
in ASCII form.
WKT representations of geometry objects:
 A Point:
POINT(15 20) nocomma needed in WKT format
========================================================================

mysql>SELECTST_X(Point(15,20));

Output:
+---------------------+
| ST_X(POINT(15, 20)) |
61

+---------------------+
| 15 |
+---------------------+
 ST_X() to extract the X-coordinate from a Point object.
===============================================================
mysql>SELECTST_X(ST_GeomFromText('POINT(15 20)'))
Output:
+---------------------------------------+
| ST_X(ST_GeomFromText('POINT(15 20)')) |
+---------------------------------------+
| 15 |
+---------------------------------------+
 WKT representation converted to a Point with ST_GeomFromText().
============================================================
A LineString with four points:
LINESTRING(0 0, 10 10, 20 25, 50 60)
 The point coordinate pairs are separated by commas.
A Polygon with one exterior ring and one interior ring:

POLYGON((0 0,10 0,10 10,0 10,0 0),(5 5,7 5,7 7,5 7, 5 5))

The LENGTH() function returns the space in bytes required for value storage.
Clearing the commandprompt screen:

mysql>systemcls

Creating table:

CREATE TABLE statement to create a table with a spatial column:

To create a table named geom that has a column named g that can store values of any geometry type,
Output:

After creating table populate them with spatial Data:


Perform the conversion directly in the INSERT statement:
1. Point Insertion
a) Conversion Directly in the Insert Statement.
mysql> INSERT INTO geom VALUES (ST_GeomFromText('POINT(1 1)'));
62

Output:
Query OK, 1 row affected (0.15 sec)

mysql> SET @g = 'POINT(2 2)';


Output:
Query OK, 0 rows affected (0.00 sec)
mysql> INSERT INTO geom VALUES (ST_GeomFromText(@g));
Output:
Query OK, 1 row affected (0.14 sec)

b) conversion prior to the INSERT:


mysql> set @g=ST_GeomFromText('POINT(3 3)');
Output:
Query OK, 0 rows affected (0.00 sec)
mysql> INSERT INTO geom VALUES (@g);
Output:
Query OK, 1 row affected (0.10 sec)
Output:

C) TO retrieve the point in geometry table:

mysql> select St_astext(g) from geom;


Output:

2. Linestring insertion:

mysql> SET @g = 'LINESTRING(0 0,1 1,2 2)';


Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO geom VALUES (st_geomfromtext(@g));


Query OK, 1 row affected (0.16 sec)
=======================================================
3. Polygon Insertion:
63

The polygon is defined by the corner points of the bounding box:


POLYGON((MINX MINY, MAXX MINY, MAXX MAXY, MINX MAXY, MINX MINY))

mysql> SET @g = 'POLYGON((0 0,10 0,10 10,0 10,0 0),(5 5,7 5,7 7,5 7, 5 5))';
Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO geom VALUES (st_geomfromtext(@g));


Query OK, 1 row affected (0.14 sec)
=====================================================
4. Insertion through more complex geometry into table: (point and linestring insertion)
mysql> SET @g =
-> 'GEOMETRYCOLLECTION(POINT(1 1),LINESTRING(0 0,1 1,2 2,3 3,4
Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO geom VALUES (st_GeomCollFromText(@g));


Query OK, 1 row affected (0.15 sec)

5. Retrieval of Spatial data from table ;

mysql> SELECT st_astext(g) from geom;


+----------------------------------------------------------------+
| st_astext(g) |
+----------------------------------------------------------------+
| POINT(1 1) |
| POINT(2 2) |
| POINT(3 3) |
| LINESTRING(0 0,1 1,2 2) |
| POLYGON((0 0,10 0,10 10,0 10,0 0),(5 5,7 5,7 7,5 7,5 5)) |
| GEOMETRYCOLLECTION(POINT(1 1),LINESTRING(0 0,1 1,2 2,3 3,4 4)) |
+----------------------------------------------------------------+
6 rows in set (0.00 sec)

Output:

SPATIAL CONVERSION FUNCTIONS:


64

a) Converts a value in internal geometry format to its WKT representation and returns the string
result.
mysql> SET @g = 'LineString(1 1,2 2,3 3)';
Query OK, 0 rows affected (0.00 sec)

mysql> SELECTST_AsText(ST_GeomFromText(@g));
+--------------------------------+
| ST_AsText(ST_GeomFromText(@g)) |
+--------------------------------+
| LINESTRING(1 1,2 2,3 3) |
+--------------------------------+

1 row in set (0.00 sec)


================================================================
b) Dimension(g)
Returns the inherent dimension of the geometry value g. The result can be −1, 0, 1, or 2
 −1 for an empty geometry.

 0 for a geometry with no length and no area.


 1 for a geometry with non-zero length and zero area.
 2 for a geometry with non-zero area.
mysql> select ST_Dimension(ST_GeomFromText('LineString(1 1,2 2)'));
+------------------------------------------------------+
| ST_Dimension(ST_GeomFromText('LineString(1 1,2 2)')) |
+------------------------------------------------------+
| 1|
+------------------------------------------------------+
1 row in set (0.06 sec)
===============================================================
c) Envelope(g)
Returns the Minimum Bounding Rectangle (MBR) for the geometry value g. The result is returned as
a Polygon value.
The polygon is defined by the corner points of the bounding box:
POLYGON((MINX MINY, MAXX MINY, MAXX MAXY, MINX MAXY, MINX MINY))
mysql>SELECT ST_AsText(ST_Envelope(ST_GeomFromText('LineString(1 1,2 2)')));
+----------------------------------------------------------------+
| ST_AsText(ST_Envelope(ST_GeomFromText('LineString(1 1,2 2)'))) |
+----------------------------------------------------------------+
| POLYGON((1 1,2 1,2 2,1 2,1 1)) |
+----------------------------------------------------------------+
65

1 row in set (0.00 sec)

d. GeometryType(g)
Returns as a string the name of the geometry type of which the geometry instance g is a member. The
name will correspond to one of the instantiable Geometry subclasses.
mysql> select ST_GeometryType(ST_GeomFromText('POINT(1 1)'));
+------------------------------------------------+
| ST_GeometryType(ST_GeomFromText('POINT(1 1)')) |
+------------------------------------------------+
| POINT |
+------------------------------------------------+
1 row in set (0.00 sec)

Point Functions

A Point consists of X and Y coordinates, which may be obtained using the following functions:
X(p):

mysql> select st_x(ST_GeomFromText('Point(56.7 53.34)'));


+--------------------------------------------+
| st_x(ST_GeomFromText('Point(56.7 53.34)')) |
+--------------------------------------------+
| 56.7 |
+--------------------------------------------+
1 row in set (0.00 sec)

Y(p):
mysql> select st_y(ST_GeomFromText('Point(56.7 53.34)'));
+--------------------------------------------+
| st_y(ST_GeomFromText('Point(56.7 53.34)')) |
+--------------------------------------------+
| 53.34 |
+--------------------------------------------+
1 row in set (0.04 sec)
66

Linestring Functions:
a. EndPoint(ls)

Returns the Point that is the end point of the LineString value ls.

mysql> SET @ls = 'LineString(1 1,2 2,3 3)';

Query OK, 0 rows affected (0.00 sec)


mysql> SELECT ST_asText(ST_EndPoint(ST_GeomFromText(@ls)));
+----------------------------------------------+
| ST_asText(ST_EndPoint(ST_GeomFromText(@ls))) |
+----------------------------------------------+
| POINT(3 3) |
+----------------------------------------------+
1 row in set (0.01 sec)

b. GLength(ls)

Returns as a double-precision number the length of the LineString value ls in its associated spatial
reference.
mysql> SET @ls = 'LineString(1 1,2 2,3 3)';
Query OK, 0 rows affected (0.00 sec)

mysql> SELECTST_Length(ST_GeomFromText(@ls));
+---------------------------------+
| ST_Length(ST_GeomFromText(@ls)) |
+---------------------------------+
| 2.8284271247461903 |
+---------------------------------+
1 row in set (0.08 sec)
c.NumPoints(ls)
Returns the number of points in the LineString value ls.
mysql> select ST_NumPoints(ST_GeomfromText(@ls));
+------------------------------------+
| ST_NumPoints(ST_GeomfromText(@ls)) |
+------------------------------------+
| 3|
+------------------------------------+
1 row in set (0.00 sec)
67

Polygon functions:

Area(poly)

Returns as a double-precision number the area of the Polygon value poly, as measured in its spatial
reference system.
mysql> SET @poly = 'Polygon((0 0,0 3,3 0,0 0),(1 1,1 2,2 1,1 1))';
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT ST_Area(ST_GeomFromText(@poly));


+---------------------------------+
| ST_Area(ST_GeomFromText(@poly)) |
+---------------------------------+
| 4|
+---------------------------------+
1 row in set (0.00 sec)

============================================================

ExteriorRing(poly)

Returns the exterior ring of the Polygon value poly as a LineString.

mysql> SELECT ST_AsText(ST_ExteriorRing(ST_GeomFromText(@poly)));


+----------------------------------------------------+
| ST_AsText(ST_ExteriorRing(ST_GeomFromText(@poly))) |
+----------------------------------------------------+
| LINESTRING(0 0,0 3,3 0,0 0) |
+----------------------------------------------------+
1 row in set (0.00 sec)
68

==============================================================

InteriorRingN(poly,n)

Returns the n-th interior ring for the Polygon value poly as a LineString. Ring numbers begin at 1.

mysql> SELECT ST_AsText(ST_InteriorRingN(ST_GeomFromText(@poly),1));


+-------------------------------------------------------+
| ST_AsText(ST_InteriorRingN(ST_GeomFromText(@poly),1)) |
+-------------------------------------------------------+
| LINESTRING(1 1,1 2,2 1,1 1) |
+-------------------------------------------------------+
1 row in set (0.00 sec)

Output:

Result:
Thus the above program has been successfully completed and executed.
69

EXP NO:5
TEMPORAL DATA STORAGE AND RETRIEVAL IN MYSQL
DATE:
Aim:
To perform Temporal data storage and Retrieval in Mysql.
Prerequisites:

Basics of Termporal Data base:


The date and time data types for representing temporal values
are DATE, TIME, DATETIME, TIMESTAMP, and YEAR
The MySQL date and time datatypes are as follows –
Data Type “Zero” Value
DATE '0000-00-00'
TIME '00:00:00'
DATETIME '0000-00-00 00:00:00'
TIMESTAMP '0000-00-00 00:00:00'
YEAR 0000

 DATE − A date in YYYY-MM-DD format, between 1000-01-01 and 9999-12-31. For example,
December 30th, 1973 would be stored as 1973-12-30.
: CONVERT_TZ(), DATE_ADD(), DATE_SUB(), DAYOFYEAR(), TIMESTAMPDIFF(), TO_D
AYS(), TO_SECONDS(), WEEK(), WEEKDAY(), WEEKOFYEAR(), YEARWEEK().
=================================================
a. To retrieve Global timezone and session timezone:
mysql> SELECT @@global.time_zone, @@session.time_zone;
Output:
+--------------------+---------------------+
| @@global.time_zone | @@session.time_zone |
+--------------------+---------------------+
| SYSTEM | SYSTEM |
+--------------------+---------------------+
1 row in set (0.02 sec)
==============================================================
b.ADDDATE(date,INTERVAL expr unit), ADDDATE(expr,days):
mysql> SELECT ADDDATE('2021-01-08', INTERVAL 31 DAY);
Output:
+----------------------------------------+
| ADDDATE('2021-01-08', INTERVAL 31 DAY) |
+----------------------------------------+
| 2021-02-08 |
+----------------------------------------+
1 row in set (0.00 sec)
C:ADDTIME(expr1,expr2):
ADDTIME() adds expr2 to expr1 and returns the result. expr1 is a time or datetime expression, and expr2 is
a time expression
70

mysql> SELECT ADDTIME('2021-3-18 23:59:59.999999', '1 1:1:1.000002');


+--------------------------------------------------------+
| ADDTIME('2021-3-18 23:59:59.999999', '1 1:1:1.000002') |
+--------------------------------------------------------+
| 2021-03-20 01:01:01.000001 |
+--------------------------------------------------------+
1 row in set (0.00 sec)

d. Findout current Zone:

mysql> SELECT @@system_time_zone;

Output:
+---------------------+
| @@system_time_zone |
+---------------------+
| India Standard Time |
+---------------------+
1 row in set (0.00 sec)
==================================================================
e.InsertingTime_zone:
mysql> CREATE TABLE ts (id INTEGER NOT NULL AUTO_INCREMENT PRIMARY
KEY,col TIMESTAMP NOT NULL) AUTO_INCREMENT = 1;
Query OK, 0 rows affected (1.35 sec)

mysql> INSERT INTO ts (col) VALUES ('2021-01-01 10:10:10'),('2021-02-01 05:20:10'),('2021-


03-17 20:10:05');
Query OK, 3 rows affected (0.17 sec)
Records: 3 Duplicates: 0 Warnings: 0

mysql> SET @@time_zone = '+00:00';


Query OK, 0 rows affected (0.02 sec)

mysql> SELECT col, UNIX_TIMESTAMP(col) FROM ts ORDER BY id;


+---------------------+---------------------+
| col | UNIX_TIMESTAMP(col) |
+---------------------+---------------------+
| 2021-01-01 04:40:10 | 1609476010 |
| 2021-01-31 23:50:10 | 1612137010 |
| 2021-03-17 14:40:05 | 1615992005 |
+---------------------+---------------------+
3 rows in set (0.04 sec)
71

f. Inserting Time values into table:


mysql> CREATE TABLE dt (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,col DATETIME
NOT NULL) AUTO_INCREMENT = 1;

Query OK, 0 rows affected (1.51 sec)

mysql> INSERT INTO dt (col) VALUES ('2020-01-01 10:10:10'),('2020-01-01 10:10:10+05:30'), ('2020-01-


01 10:10:10-08:00');
Query OK, 3 rows affected (0.11 sec)
Records: 3 Duplicates: 0 Warnings: 0
Query OK, 3 rows affected (0.11 sec)
Records: 3 Duplicates: 0 Warnings: 0
==========================================================================
mysql> SELECT col, UNIX_TIMESTAMP(col) FROM dt ORDER BY id;
+---------------------+---------------------+
| col | UNIX_TIMESTAMP(col) |
+---------------------+---------------------+
| 2020-01-01 10:10:10 | 1577873410 |
| 2020-01-01 04:40:10 | 1577853610 |
| 2020-01-01 18:10:10 | 1577902210 |
+---------------------+---------------------+
2 rows in set (0.00 sec)
72

=====================================================================
g.CONVERT_TZ(dt,from_tz,to_tz):

CONVERT_TZ() converts a datetime value dt from the time zone given by from_tz to the time zone given
by to_tz and returns the resulting value.

Date and Time Data Type Syntax

 DATETIME − A date and time combination in YYYY-MM-DD HH:MM:SS format, between 1000-
01-01 00:00:00 and 9999-12-31 23:59:59. For example, 3:30 in the afternoon on December 30th,
1973 would be stored as 1973-12-30 15:30:00.
 TIMESTAMP − A timestamp between midnight, January 1st, 1970 and sometime in 2037. This
looks like the previous DATETIME format, only without the hyphens between numbers; 3:30 in the
afternoon on December 30th, 1973 would be stored as 19731230153000 ( YYYYMMDDHHMMSS
).
 TIME − Stores the time in a HH:MM:SS format.
 YEAR(M) − Stores a year in a 2-digit or a 4-digit format. If the length is specified as 2 (for example
YEAR(2)), YEAR can be between 1970 to 2069 (70 to 69). If the length is specified as 4, then
YEAR can be 1901 to 2155. The default length is 4.
Date function:
 CURDATE()
Return s the current date as a value in 'YYYY-MM-DD' or YYYYMMDD format,
DATEDIFF() returns expr1 − expr2 expressed as a value in days from one date to the
other. expr1 and expr2 are date or date-and-time expressions. Only the date parts of the values are
used in the calculation.
Output:
73

TIMESTAMP IN MYSQL
a. ADD() method:
mysql> SELECT TIMESTAMPADD(MONTH,2,'2009-05-18');
Output:
+------------------------------------+
| TIMESTAMPADD(MONTH,2,'2009-05-18') |
+------------------------------------+
| 2009-07-18 |
+------------------------------------+
1 row in set (0.00 sec)
b.CONVERT TIMEZONE:
mysql> SELECT CONVERT_TZ('2008-05-15 12:00:00','+00:00','+10:00');
Output:
+-----------------------------------------------------+
| CONVERT_TZ('2008-05-15 12:00:00','+00:00','+10:00') |
+-----------------------------------------------------+
| 2008-05-15 22:00:00 |
+-----------------------------------------------------+
1 row in set (0.00 sec)
c.CURRENT_TIMESTAMP method:
mysql> SELECT CURRENT_TIMESTAMP;
Output:
+---------------------+
| CURRENT_TIMESTAMP |
+---------------------+
| 2022-07-26 12:30:59 |
+---------------------+
1 row in set (0.00 sec)
d.UNIXTIMESTAMP():
mysql> SELECT UNIX_TIMESTAMP();
74

Output:
+------------------+
| UNIX_TIMESTAMP() |
+------------------+
| 1658928829 |
+------------------+
1 row in set (0.00 sec)
e.CREATE TABLE WITH TIMESTAMP:
mysql> CREATE TABLE test_timestamp (
-> t1 TIMESTAMP
-> );

Query OK, 0 rows affected (4.32 sec)

mysql> SET time_zone='+00:00';

Query OK, 0 rows affected (0.00 sec)


==============================================
f.Inserting values into table:

mysql> INSERT INTO test_timestamp(t1)


->VALUES('2008-01-01 00:00:01');

Query OK, 1 row affected (6.37 sec)

mysql> SELECT t1 FROM test_timestamp;


+---------------------+
| t1 |
+---------------------+
| 2008-01-01 00:00:01 |
+---------------------+
1 row in set (0.00 sec)
===========================================================
g.updatingtimezone into table:

mysql> SET time_zone ='+03:00';


Query OK, 0 rows affected (0.00 sec)

mysql> SELECT t1 FROM test_timestamp;


+---------------------+
| t1 |
+---------------------+
| 2008-01-01 03:00:01 |
+---------------------+
1 row in set (0.00 sec)
==========================================================
h.Creating the table with current timestamp values:
75

mysql> CREATE TABLE categories (


-> id INT AUTO_INCREMENT PRIMARY KEY,
-> name VARCHAR(255) NOT NULL,
->created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-> );
Output:
Query OK, 0 rows affected (0.38 sec)

mysql> INSERT INTO categories(name)


-> VALUES ('A');
Output:
Query OK, 1 row affected (0.32 sec)

mysql> SELECT * FROM categories;

Output:
+----+------+---------------------+
| id | name | created_at |
+----+------+---------------------+
| 1 | A | 2022-07-31 16:29:11 |
+----+------+---------------------+
1 row in set (0.00 sec)
==========================================================
mysql> ALTER TABLE categories
-> ADD COLUMN updated_at
-> TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-> ON UPDATE CURRENT_TIMESTAMP;
Output:
Query OK, 0 rows affected (1.22 sec)
Records: 0 Duplicates: 0 Warnings: 0
========================================================
mysql> INSERT INTO categories(name)
-> VALUES('B');

Output:

Query OK, 1 row affected (0.16 sec)


=======================================================
mysql> SELECT * FROM categories;

Output:

+----+------+---------------------+---------------------+
| id | name | created_at | updated_at |
+----+------+---------------------+---------------------+
| 1 | A | 2022-07-31 16:29:11 | 2022-07-31 16:29:34 |
| 2 | B | 2022-07-31 16:29:45 | 2022-07-31 16:29:45 |
+----+------+---------------------+---------------------+
2 rows in set (0.00 sec)
76

===========================================================
mysql> UPDATE categories
-> SET name = 'B+'
-> WHERE id = 2;
Output:

Query OK, 1 row affected (0.12 sec)


Rows matched: 1 Changed: 1 Warnings: 0

mysql> SELECT *
-> FROM categories
-> WHERE id = 2;
Output:

+----+------+---------------------+---------------------+
| id | name | created_at | updated_at |
+----+------+---------------------+---------------------+
| 2 | B+ | 2022-07-31 16:29:45 | 2022-07-31 16:30:00 |
+----+------+---------------------+---------------------+
1 row in set (0.02 sec)

2.DATE IN MYSQL
CURRENT DATE() method
mysql> SELECT CURDATE();
Output:

+------------+
| CURDATE() |
+------------+
| 2022-07-26 |
+------------+
1 row in set (0.00 sec)
=========================================================
ADD() method
mysql> SELECT DATE_ADD('2008-05-15',INTERVAL 10 DAY);
Output:

+----------------------------------------+
| DATE_ADD('2008-05-15',INTERVAL 10 DAY) |
+----------------------------------------+
| 2008-05-25 |
+----------------------------------------+
1 row in set (0.00 sec)
========================================================
DATE FORMAT()
mysql> select date_format('2022-07-26 12:46:00', '%W %D %M %Y');
77

Output:

+---------------------------------------------------+
| date_format('2022-07-26 12:46:00', '%W %D %M %Y') |
+---------------------------------------------------+
| Tuesday 26th July 2022 |
+---------------------------------------------------+
1 row in set (0.00 sec)
=========================================================
DATE DIFFERENCE():
mysql> SELECT DATEDIFF('2022-05-17 11:31:31','2022-04-28');
Output:

+----------------------------------------------+
| DATEDIFF('2022-05-17 11:31:31','2022-04-28') |
+----------------------------------------------+
| 19 |
+----------------------------------------------+
1 row in set (0.00 sec)
=======================================================
CREATE TABLE with date column:
mysql> create table people1(id INT AUTO_INCREMENT PRIMARY KEY,first_name
VARCHAR(50) NOT NULL,last_name VARCHAR(50) NOT NULL,birth_date DATE NOT
NULL);
Output:

Query OK, 0 rows affected (1.58 sec)


========================================================
INSERTING VALUES IN TO TABLE with date column:
mysql> INSERT INTO people1(first_name,last_name,birth_date) VALUES('John','Doe','1990-09-
01');
Output:

Query OK, 1 row affected (0.31 sec)


RETRIEVING VALUES FROM TABLE:
mysql> SELECT first_name,last_name,birth_date FROM people1;
Output:

+------------+-----------+------------+
| first_name | last_name | birth_date |
+------------+-----------+------------+
| John | Doe | 1990-09-01 |
+------------+-----------+------------+
1 row in set (0.00 sec)
=======================================================

INSERT INTO people1(first_name,last_name,birth_date) VALUES('Jack','Daniel','01-09-


01'),('Lily','Bush','80-09-01');
78

Output:

Query OK, 2 rows affected (0.61 sec)


Records: 2 Duplicates: 0 Warnings: 0

mysql> SELECT
->first_name,
->last_name,
->birth_date
-> FROM
-> people1;
=====================================================
Output:

+------------+-----------+------------+
| first_name | last_name | birth_date |
+------------+-----------+------------+
| John | Doe | 1990-09-01 |
| Jack | Daniel | 2001-09-01 |
| Lily | Bush | 1980-09-01 |
+------------+-----------+------------+
3 rows in set (0.01 sec)
=====================================================

3.TIME IN MYSQL
CURRENT_TIME method
mysql> SELECT CURRENT_TIME;
Output:

+--------------+
| CURRENT_TIME |
+--------------+
| 12:30:10 |
+--------------+
1 row in set (0.00 sec)
====================================================
LOCAL TIME

mysql> SELECT LOCALTIME;


Output:

+---------------------+
| LOCALTIME |
+---------------------+
| 2022-07-26 12:56:13 |
+---------------------+
1 row in set (0.00 sec)
TIME FORMAT()
mysql>SELECT TIME_FORMAT('97:15:40','%H %k %h %I %l');
79

Output:

+------------------------------------------+
| TIME_FORMAT('97:15:40','%H %k %h %I %l') |
+------------------------------------------+
| 97 97 01 01 1 |
+------------------------------------------+
1 row in set (0.09 sec)
=====================================================
CREATE TABLE
mysql> CREATE TABLE tests (
-> id INT PRIMARY KEY AUTO_INCREMENT,
-> name VARCHAR(255) NOT NULL,
->start_at TIME,
->end_at TIME
-> );
Output:

Query OK, 0 rows affected (0.65 sec)


======================================================
mysql> INSERT INTO tests(name,start_at,end_at)
->VALUES('Test 1', '08:00:00','10:00:00');
Output:

Query OK, 1 row affected (0.21 sec)


======================================================

mysql> SELECT
-> name, start_at, end_at
-> FROM
-> tests;
Output:

+--------+----------+----------+
| name | start_at | end_at |
+--------+----------+----------+
| Test 1 | 08:00:00 | 10:00:00 |
+--------+----------+----------+
1 row in set (0.00 sec)
======================================================
mysql> INSERT INTO tests(name,start_at,end_at)
->VALUES('Test 2','083000','101500');
Output:

Query OK, 1 row affected (0.24 sec)


=======================================================
mysql> INSERT INTO tests(name,start_at,end_at)
->VALUES('Test 3',082000,102000);
80

Output:

Query OK, 1 row affected (0.18 sec)


=======================================================
mysql> INSERT INTO tests(name,start_at,end_at)
->VALUES('Test 4','9:5:0',100500);
Output:

Query OK, 1 row affected (0.12 sec)


=======================================================
mysql> SELECT
-> CURRENT_TIME() AS string_now,
-> CURRENT_TIME() + 0 AS numeric_now;
Output:

+------------+-------------+
| string_now | numeric_now |
+------------+-------------+
| 16:25:56 | 162556 |
+------------+-------------+
1 row in set (0.05 sec)
======================================================
mysql> SELECT
-> CURRENT_TIME(),
-> ADDTIME(CURRENT_TIME(), 023000),
-> SUBTIME(CURRENT_TIME(), 023000);
Output:

+----------------+---------------------------------+---------------------------------+
| CURRENT_TIME() | ADDTIME(CURRENT_TIME(), 023000) | SUBTIME(CURRENT_TIME(),
023000) |
+----------------+---------------------------------+---------------------------------+
| 16:26:09 | 18:56:09 | 13:56:09 |
+----------------+---------------------------------+---------------------------------+
1 row in set (0.06 sec)
=====================================================
mysql> SELECT
->TIMEDIFF(end_at, start_at)
-> FROM
-> tests;
Output:

+----------------------------+
| TIMEDIFF(end_at, start_at) |
+----------------------------+
| 02:00:00 |
| 01:45:00 |
| 02:00:00 |
| 01:00:00 |
81

+----------------------------+
4 rows in set (0.07 sec)
======================================================
mysql> SELECT
-> name,
-> TIME_FORMAT(start_at, '%h:%i %p') start_at,
-> TIME_FORMAT(end_at, '%h:%i %p') end_at
-> FROM
-> tests;
Output:

+--------+----------+----------+
| name | start_at | end_at |
+--------+----------+----------+
| Test 1 | 08:00 AM | 10:00 AM |
| Test 2 | 08:30 AM | 10:15 AM |
| Test 3 | 08:20 AM | 10:20 AM |
| Test 4 | 09:05 AM | 10:05 AM |
+--------+----------+----------+
4 rows in set (0.03 sec)

======================================================
mysql> SELECT
-> CURRENT_TIME(),
-> UTC_TIME();
Output:

+----------------+------------+
| CURRENT_TIME() | UTC_TIME() |
+----------------+------------+
| 16:26:59 | 13:26:59 |
+----------------+------------+
1 row in set (0.00 sec)
=====================================================
4.DATETIME IN MySQL:
mysql> SELECT
-> HOUR(@dt),
-> MINUTE(@dt),
-> SECOND(@dt),
-> DAY(@dt),
-> WEEK(@dt),
-> MONTH(@dt), mysql> CREATE TABLE test_dt (
-> id INT AUTO_INCREMENT PRIMARY KEY,
->created_at DATETIME
-> );

Output:
Query OK, 0 rows affected (0.81 sec)
82

mysql> INSERT INTO test_dt(created_at)


->VALUES('2015-11-05 14:29:36');
Query OK, 1 row affected (0.29 sec)
======================================================
mysql> SELECT
-> *
-> FROM
->test_dt
-> WHERE
->created_at = '2015-11-05';
Empty set (0.27 sec)
=====================================================
mysql> SELECT
-> *
-> FROM
->test_dt
-> WHERE
->DATE(created_at) = '2015-11-05';
Output:

+----+---------------------+
| id | created_at |
+----+---------------------+
| 1 | 2015-11-05 14:29:36 |
+----+---------------------+
1 row in set (0.00 sec)
======================================================
mysql> SELECT
-> *
-> FROM
->test_dt
-> WHERE
->DATE(created_at) = '2015-11-05';
+----+---------------------+
| id | created_at |
+----+---------------------+
| 1 | 2015-11-05 14:29:36 |
+----+---------------------+
1 row in set (0.00 sec)
======================================================
mysql> SELECT TIME(@dt);
+-----------------+
| TIME(@dt) |
+-----------------+
| 16:18:52.000000 |

-> QUARTER(@dt),
-> YEAR(@dt);
+-----------+-------------+-------------+----------+-----------+------------+--------------+-----------+
83

| HOUR(@dt) | MINUTE(@dt) | SECOND(@dt) | DAY(@dt) | WEEK(@dt) | MONTH(@dt) |


QUARTER(@dt) | YEAR(@dt) |
+-----------+-------------+-------------+----------+-----------+------------+--------------+-----------+
| 16 | 18 | 52 | 31 | 31 | 7| 3 | 2022 |
+-----------+-------------+-------------+----------+-----------+------------+--------------+-----------+
1 row in set (0.03 sec)
====================================================
5.TIMESTAMP and DATETIME:

mysql>SET time_zone = '+00:00';

Query OK, 0 rows affected (0.13 sec)


=====================================================
CREATE TABLE
mysql> CREATE TABLE timestamp_n_datetime (
-> id INT AUTO_INCREMENT PRIMARY KEY,
->ts TIMESTAMP,
-> dt DATETIME
-> );
Output:

Query OK, 0 rows affected (2.63 sec)


=====================================================
mysql> INSERT INTO timestamp_n_datetime(ts,dt)
-> VALUES(NOW(),NOW());
Output:

Query OK, 1 row affected (0.55 sec)


======================================================
mysql> SELECT
->ts,
-> dt
-> FROM
->timestamp_n_datetime;

Output:

+---------------------+---------------------+
| ts | dt |
+---------------------+---------------------+
| 2022-07-31 13:15:32 | 2022-07-31 13:15:32 |
+---------------------+---------------------+
1 row in set (0.00 sec)

mysql> SET time_zone = '+03:00';


Output:

Query OK, 0 rows affected (0.00 sec)


======================================================
84

mysql>
mysql> SELECT
->ts,
-> dt
-> FROM
->timestamp_n_datetime;
Output:

+---------------------+---------------------+
| ts | dt |
+---------------------+---------------------+
| 2022-07-31 16:15:32 | 2022-07-31 13:15:32 |
+---------------------+---------------------+
1 row in set (0.00 sec)
====================================================
mysql> SET @dt = NOW();
Output:
Query OK, 0 rows affected (0.15 sec)
=====================================================
mysql> SELECT DATE(@dt);
Output:

+------------+
| DATE(@dt) |
+------------+
| 2022-07-31 |
+------------+
1 row in set (0.00 sec)

mysql> SELECT DATE(@dt);


Output:

+------------+
| DATE(@dt) |
+------------+
| 2022-07-31 |
+------------+
1 row in set (0.00 sec)

+-----------------+
1 row in set (0.00 sec)
=======================================================

RESULT:

Thus the above program has been successfully completed and executed
85

EXP NO: 6
OBJECT DATABASES
DATE:

Aim:
To perform Object Storage and Retrieval from Mysql Database.
DESCRIPTION:

MySQL Stored Procedure


A procedure (often called a stored procedure) is a collection of pre-compiled SQL statements stored
inside the database. It is a subroutine or a subprogram in the regular computing language. A procedure
always contains a name, parameter lists, and SQL statements. We can invoke the procedures by using
triggers, other procedures and applications such as Java, Python, PHP, etc. It was first introduced in
MySQL version 5. Presently, it can be supported by almost all relational database systems.
How to create a procedure?

The following syntax is used for creating a stored procedure in MySQL. It can return one or more value
through parameters or sometimes may not return at all. By default, a procedure is associated with our
current database. But we can also create it into another database from the current database by specifying
the name as database_name.procedure_name. See the complete syntax:
1. DELIMITER &&
2. CREATE PROCEDURE procedure_name [[IN | OUT | INOUT] parameter_name datatype [,
parameter datatype]) ]
3. BEGIN
4. Declaration_section
5. Executable_section
6. END &&
7. DELIMITER ;
Defining Stored Programs
Each stored program contains a body that consists of an SQL statement. This statement may be a compound
statement made up of several statements separated by semicolon (;) characters.

Skeleton of stored procedure:


 Stored procedure has a body made up of a BEGIN ... END block
 That contains a SET statement
 A REPEAT loop that itself contains another SET statement:
86

To redefine the mysql delimiter, use the delimiter command.


MySQL procedure parameter has one of three modes:
IN parameter
It is the default mode. It takes a parameter as input, such as an attribute. When we define it, the calling
program has to pass an argument to the stored procedure. This parameter's value is always protected.
OUT parameters
It is used to pass a parameter as output. Its value can be changed inside the stored procedure, and the
changed (new) value is passed back to the calling program. It is noted that a procedure cannot access the
OUT parameter's initial value when it starts.
INOUT parameters
It is a combination of IN and OUT parameters. It means the calling program can pass the argument, and
the procedure can modify the INOUT parameter, and then passes the new value back to the calling
program.
How to call a stored procedure?
We can use the CALL statement to call a stored procedure. This statement returns the values to its caller
through its parameters (IN, OUT, or INOUT). The following syntax is used to call the stored procedure
in MySQL:
1. CALL procedure_name ( parameter(s))
Example
Let us understand how to create a procedure in MySQL through example. First, we need to select a
database that will store the newly created procedure. We can select the database using the below
statement:
mysql> delimiter //
======================================================
mysql> CREATE PROCEDURE dorepeat(p1 INT)
-> BEGIN
-> set @x=0;
-> repeat SET @x = @x + 1; UNTIL @x > p1 END REPEAT;
-> end
-> //
Output:
Query OK, 0 rows affected (0.16 sec)
===================================================
mysql>delimiter ;
mysql> call dorepeat(10);
Output:
Query OK, 0 rows affected (0.03 sec)
mysql> select @x;
Output:
+------+
| @x |
+------+
| 11 |
+------+
1 row in set (0.00 sec)
Output:
87

A function that takes a parameter, performs an operation using an SQL function, and returns the result
mysql> CREATE FUNCTION hello (s CHAR(20))
-> RETURNS CHAR(50) DETERMINISTIC
-> RETURN CONCAT('Hello, ',s,'!');
Output:
Query OK, 0 rows affected (0.21 sec)
mysql> select hello('srimathi welcome');
Output:
+---------------------------+
| hello('srimathi welcome') |
+---------------------------+
| Hello, srimathi welcome! |
+---------------------------+
1 row in set (0.00 sec)
Output:

Count() procedure:
mysql> select * from student;
88

Output:

+------+-----------+------+-------+
| sno |sname | dept | marks |
+------+-----------+------+-------+
| 10 | srimathi |mca | 70 |
| 20 | kavi | mca | 80 |
| 30 | madhu | mba | 75 |
| 40 | john | mba | 55 |
| 50 | kavipriya | mba | 59 |
+------+-----------+------+-------+
5 rows in set (0.00 sec)

mysql> delimiter &&


mysql> CREATE PROCEDURE get_merit_student ()
-> BEGIN
-> SELECT * FROM student where marks >60;
-> select count(sno) as total_merit from student;
-> end &&

Output:
Query OK, 0 rows affected (0.11 sec)
mysql>delimiter ;
mysql> call get_merit_student();

Output:

+------+----------+------+-------+
| sno |sname | dept | marks |
+------+----------+------+-------+
| 10 | srimathi | mca | 70 |
| 20 | kavi | mca | 80 |
| 30 | madhu | mba | 75 |
+------+----------+------+-------+
3 rows in set (0.05 sec)
+-------------+
| total_merit |
+-------------+
| 5|
+-------------+
1 row in set (0.06 sec)

Query OK, 0 rows affected (0.06 sec)


89

mysql> DELIMITER &&


mysql>
mysql> CREATE PROCEDURE get_student (IN var1 INT)
-> BEGIN
-> SELECT * FROM student limit var1;
-> select count(sno) as total_student from student;
-> end&&
Output:
Query OK, 0 rows affected (0.11 sec)
mysql>delimiter ;
mysql> call get_student(2);
Output:
+------+----------+------+-------+
| sno |sname | dept | marks |
+------+----------+------+-------+
| 10 | srimathi | mca | 70 |
| 20 | kavi | mca | 80 |
+------+----------+------+-------+
2 rows in set (0.00 sec)
+---------------+
| total_student |
+---------------+
| 5|
+---------------+
1 row in set (0.01 sec)
Query OK, 0 rows affected (0.01 sec)

Output:
90

Procedures with OUT Parameter


mysql> DELIMITER &&
mysql> CREATE PROCEDURE display_max_mark (OUT highestmark INT)
-> BEGIN
-> SELECT MAX(marks) INTO highestmark FROM student;
-> end &&
Output:
Query OK, 0 rows affected (0.15 sec)
=====================================================
mysql>delimiter ;
mysql> call display_max_mark(@m);
Query OK, 1 row affected (0.08 sec)

mysql> select @m;


+------+
| @m |
+------+
| 80 |
+------+
1 row in set (0.00 sec)
91

Procedures with INOUT Parameter

mysql> delimiter &&


mysql> CREATE PROCEDURE display_marks (INOUT var1 INT)
-> BEGIN
-> SELECT marks INTO var1 FROM student WHERE sno = var1;
-> END &&
Output:

Query OK, 0 rows affected (0.18 sec)

mysql>delimiter ;
mysql> set @m=30;
Output:

Query OK, 0 rows affected (0.00 sec)

mysql> call display_marks(@m);

Output:
Query OK, 1 row affected (0.03 sec)

mysql> select @m;


+------+
| @m |
+------+
| 75 |
+------+
1 row in set (0.00 sec)

TO VIEW THE STATUS OF PROCEDURE CREATED ON TABLE IN DB:

mysql> SHOW PROCEDURE STATUS WHERE db ='sriviims';


92

RESULT:

Thus the above program has been successfully completed and executed
93

EXP NO:7
XML DATABASES
DATE:

Aim:
To perform table creation in XML,XQUERY FLWOR EXPRESSION
DESCRIPTION:
XML CREATION WITH INTERNAL DTD:
First.xml:
<?xml version="1.0"?>
<!DOCTYPE student[
<!ELEMENT student (viimsmca)*>
<!ELEMENT viimsmca (sno,sname,age,photo)+>
<!ELEMENT sno (#PCDATA)>
<!ELEMENT sname (#PCDATA)>
<!ELEMENT age (#PCDATA)>
<!ELEMENT photo (#PCDATA)>
<!ATTLIST age DOB CDATA #REQUIRED>
<!ATTLIST sname regno ID #REQUIRED>
<!ATTLIST sname friendid1 IDREF #IMPLIED>
<!ATTLIST sname friendid2 IDREF #IMPLIED>
<!ATTLIST photo image ENTITY #REQUIRED>
<!ENTITY s1 PUBLIC "-//W3C//GIF logo//EN" "http://www.w3.org/logo.gif" NDATA gif>
<!NOTATION gif PUBLIC "gif viewer">
]>
<student>
<viimsmca>
<sno>1</sno>
<sname regno="a61339992" friendid1="a61339993">sri</sname>
<age DOB="10-10-1981">30</age>
<photo image="s1"/>
</viimsmca>
<viimsmca>
<sno>2</sno>
<sname regno="a61339993">kavii</sname>
<age DOB="10-10-1981">30</age>
<photo image="s1"/>
</viimsmca>
</student>
94

=========================================================
Loading xml in DOM Parser:
My1.html
<html>
<body>
<p id="demo"></p>
<script>
alert("Hi...Opening XML Document");
var x1 = new ActiveXObject("MicroSoft.xmldom");
x1.load("first.xml");
alert("Loaded...");
alert(x1.xml);
alert(x1.documentElement.text);
function load_document()
{
if(x1.readyState==4)
begin();
else
window.setTimeout("load_document()",3000);
}
function begin()
{
var root=x1.documentElement;
var rec1 = root.childNodes.item(0);
var rec2 = root.childNodes.item(1);
alert("Root Name : "+ root.nodeName);
alert("Child Name : " +rec1.nodeName);
alert("1st Record");
alert(rec1.childNodes.item(0).nodeName + " : " +rec1.childNodes.item(0).text);
alert(rec1.childNodes.item(1).nodeName + " : " +rec1.childNodes.item(1).text);
alert(rec1.childNodes.item(2).nodeName + " : " +rec1.childNodes.item(2).text);
alert(rec1.childNodes.item(3).nodeName + " : " +rec1.childNodes.item(3).text);
}
</script>
</head>
<body bgcolor="pink" text="blue" onload="load_document()">
<h1>student Informations....</h1>
</script>
</body>
</html>

===========================================
95

XQuery FLWOR Expressions


What is FLWOR?

FLWOR (pronounced "flower") is an acronym for "For, Let, Where, Order by, Return".

 For - selects a sequence of nodes


 Let - binds a sequence to a variable
 Where - filters the nodes
 Order by - sorts the nodes
 Return - what to return (gets evaluated once for every node)

Book.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" cover="paperback">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
===============================================================
96

XQUERY:

XQuery uses path expressions to navigate through elements in an XML document.

Select Nodes From "books.xml" With FLWOR


a.select all the title elements under the book elements that are under the bookstore element that have a price
element with a value that is higher than 30
Ex:
doc("books.xml")/bookstore/book[price>30]/title

for $x in doc("books.xml")/bookstore/book
where $x/price>30
return $x/title
❮ PreviousNext ❯
Output:

<title lang="en">XQuery Kick Start</title>


<title lang="en">Learning XML</title>
==========================================================================
b:sort the result in ascending order:
for $x in doc("books.xml")/bookstore/book
where $x/price>30
order by $x/title
return $x/title

Output:
<title lang="en">Learning XML</title>

<title lang="en">XQuery Kick Start</title

RESULT;

Thus the above program has been successfully completed and executed.

You might also like