advanced datbase technology lab-final
advanced datbase technology lab-final
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
Gotohttps://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
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
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
>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 }
===============================================
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
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
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.
Step 4: Start Cassandra from Windows CMD as C:\apache-cassandra-3.11.10\bin and type the
following
cassandra
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
Result:
Thus the above program has been successfully completed and executed
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
Hadoop datanode
http://localhost:50075/datanode.html
D:\hive\apache-hive-2.1.0-bin\bin>
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
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
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)
The following dialogue box shows the partition values based on course :
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 ^
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 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.
http://localhost:2480/studio/index.html#/
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
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
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:
SELECT QUERY:
a) Using where clause:
mysql> select * from emp where ename='srimathi';
+------+----------+------+
| eno |ename | sal |
+------+----------+------+
| 2 | Srimathi | 4000 |
+------+----------+------+
51
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)
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)
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.
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
/
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
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:
Step3click phpmyadim
Step4 give username as root and password as empty
Step5 click replication tab
EXP NO: 4
SPATIAL DATA STORAGE AND RETRIEVAL IN MYSQL
DATE:
Aim:
To perform Spatial Data storage and retrieval in Mysql.
Prerequisites:
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:
To create a table named geom that has a column named g that can store values of any geometry type,
Output:
Output:
Query OK, 1 row affected (0.15 sec)
2. Linestring insertion:
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)
Output:
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) |
+--------------------------------+
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):
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.
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)
============================================================
ExteriorRing(poly)
==============================================================
InteriorRingN(poly,n)
Returns the n-th interior ring for the Polygon value poly as a LineString. Ring numbers begin at 1.
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:
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
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)
=====================================================================
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.
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
-> );
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:
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:
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:
+------------+-----------+------------+
| first_name | last_name | birth_date |
+------------+-----------+------------+
| John | Doe | 1990-09-01 |
+------------+-----------+------------+
1 row in set (0.00 sec)
=======================================================
Output:
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
+---------------------+
| 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:
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:
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
+----+---------------------+
| 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
Output:
+---------------------+---------------------+
| ts | dt |
+---------------------+---------------------+
| 2022-07-31 13:15:32 | 2022-07-31 13:15:32 |
+---------------------+---------------------+
1 row in set (0.00 sec)
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)
+------------+
| 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:
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.
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)
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)
Output:
90
mysql>delimiter ;
mysql> set @m=30;
Output:
Output:
Query OK, 1 row affected (0.03 sec)
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
FLWOR (pronounced "flower") is an acronym for "For, Let, Where, Order by, Return".
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:
for $x in doc("books.xml")/bookstore/book
where $x/price>30
return $x/title
❮ PreviousNext ❯
Output:
Output:
<title lang="en">Learning XML</title>
RESULT;
Thus the above program has been successfully completed and executed.