Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 22

1.

Implementation of DDL and DML Commands

Aim:

To create Queries using DDL and DML commands

Algorithm:
STEP 1: Start the process.
STEP 2: Data Manipulation Language (DML) is a family of syntax elements similar to a computer
programming language used for selecting, inserting, deleting and updating data in a database. Performing
read-only queries of data is sometimes also considered a component of DML.
Commands in DML are:
a.INSERT
b.UPDATE
c.DELETE
d.SELECT
STEP 3: Data Definition Language (DDL) is used to communicate with database. DDL is used to create an
object ,alter its structure and drop it if no longer needed
a. Create
b. Alter
c. Drop
d. Truncate
Insert records into the table student.
STEP 4: Query with appropriate syntax
STEP 6: Select all the records and view the output.
STEP 7: Stop the process.

Coding:
SYNTAX:
INSERT Statement:
Single Row into a Table: INSERT INTO table – name [column- identifier-comma-list)] VALUES
(column-valuecomma-list);
Multiple Row into a Table: insert into <table name> values (&col1, &col2, ….);
UPDATE Statement: UPDATE table-name SET update- column-list [WHERE search- condition];
DELETE Statement: DELETE FROM table-name [WHERE search- condition];
DDL: A data definition language or data description language (DDL) is syntax similar to a
computer programming language for defining data structures, especially database schemas.
DDL COMMANDS:
SYNTAX:
CREATE Statement: Create table tablename (column_name1 data_ type constraints, column_name2
data_ type constraints);
DROP:DROP TABLE table_name;
TRUNCATE: TRUNCATE TABLE table_name;
RENAME: RENAME TABLE {tbl_name} TO {new_tbl_name};
ALTER:
Add column to Table: ALTER TABLE table_name ADD column_name column-definition; Modify column
in Table: ALTER TABLE table_name MODIFY column_namecolumn_type; Drop column in

Table:ALTER TABLE table_name DROP COLUMN column_name;

DDL QUERIES:
Q1. Write a query to create a table employee with empno, ename, designation, andsalary. SQL>CREATE
TABLE EMP (EMPNO NUMBER (4),
ENAME VARCHAR2 (10),
DESIGNATIN VARCHAR2 (10),
SALARY NUMBER (8,2));
Table created.
Q2. Write a query for create a from an existing table with all the fields. SQL>
CREATE TABLE EMP1 AS SELECT * FROM EMP;
Table created.

Q3. Write a Query to Alter the column EMPNO NUMBER(4) TO EMPNO NUMBER(6). SQL>ALTER
TABLE EMP MODIFY EMPNO NUMBER (6);
Table altered.
Q4. Write a query to add a new column in to employee.
SQL> ALTER TABLE EMP ADD QUALIFICATION VARCHAR2(6);
Table altered.
Q5. Write a query to drop a column from an existing table employee.
SQL> ALTER TABLE EMP DROP COLUMN DOJ;
Table altered.
Q6. Write a query to drop an existing table employee.
SQL> DROP table employee;
Table deleted.
DML QUERIES:
Q1. Write a query to insert the records in to employee.
SQL>INSERT INTO EMP VALUES(103,'Saurabh','ASST_PROF',25000);
1 row created.
Q2. Write a query to display the records from employee. SQL>
SELECT * FROM EMP;
EMPNO ENAME DESIGNATIN SALARY
---------- ------------ ---------- ----------
103 SAURABH ASST_PROF 25000
Q3. Write a query to insert the records in to employee using substitution method.
SQL> INSERT INTO EMP
VALUES(&EMPNO,'&ENAME','&DESIGNATIN','&SALARY');
Enter value for empno: 102
Enter value for ename: DHAJVEER Enter
value for designatin: ASST_PROF Enter
value for salary: 35000

old 1: INSERT INTO EMP VALUES(&EMPNO,'&ENAME','&DESIGNATIN','&SALARY')


new 1: INSERT INTO EMP VALUES(102,'DHAJVEER','ASST_PROF','35000')
1 row created.
SQL> /
Enter value for empno: 101
Enter value for ename: ABHILASHA Enter value
for designatin: ASST_PROF Enter value for salary:
40000
old 1: INSERT INTO EMP VALUES(&EMPNO,'&ENAME','&DESIGNATIN','&SALARY')
new 1: INSERT INTO EMP VALUES(101,'ABHILASHA','ASST_PROF','40000')
1 row created.
Q4. Write a query to update the records from employee.
SQL> UPDATE EMP SET SALARY=45000 WHERE EMPNO=101;
1 row updated.
SQL> SELECT * FROM EMP;
EMPNO ENAME DESIGNATIN SALARY
---------- ------------ ---------- ----------
101 ABHILASHA ASST_PROF 45000
102 DHAJVEER ASST_PROF 35000
103 SAURABH ASST_PROF 30000

Result:
Thus the above queries are executed successfully and output is verified.
2. Database design using E-R model and Normalization
Aim:

To create a database design using ER modeler in Oracle DB Modeler with normalization concepts

Algorithm:

STEP 1: Start the process.


STEP 2: Analyze and Model Relationships with Normalization using ORACLE DB Modeler
STEP 3: Insert records into the table student.
STEP 4: Write the ERDish for each of the relationships in the Academic Database including relationship names,
optionality and cardinality
STEP 5: Draw the ERD including the relationships.
STEP 6: view the output.
STEP 7: Stop the process.

CARDINALITY : ER DIAGRAM
Solution:

1) Each ACADEMIC SESSION must schedule one or more COURSE.

Each COURSE must be scheduled in one and only one ACADEMIC SESSION.

2) Each STUDENT may enroll in one or more COURSE.

Each COURSE must have enrolled one or more STUDENT.

3) Each COURSE must be offered by one and only one

DEPARTMENT. Each DEPARTMENT may offer one or

more COURSES.

4) Each COURSE must be taught by one or more

FACULTY. Each FACULTY may teach one or

more COURSE.

5) Each DEPARTMENT may contain one or more FACULTY.

Each FACULTY must belong to one and only one DEPARTMENT.

6) Each STUDENT may have one and only one PARENT

INFORMATION. Each PARENT INFORMATION must be

for one and only one STUDENT.

7) Each STUDENT may take one or more EXAM.

Each EXAM must be taken by one or more STUDENT.

8) Each COURSE may have one or more EXAM.

9) Each EXAM must be for one and only one COURSE.


3. Impement the concept of Cursor

Aim:
To write a program to implement the concept of Cursor.

Algorithm:
STEP 1: Start the process.
STEP 2: Create a table employee with attributes such as Empid, name, department
,designation,salary,allowances and deductions.
STEP 3: Insert records into employee table.
STEP 4: cursors will perform the open, fetches, and close for you automatically. Implicit cursors are used
in statements that return only one row.
STEP 5: Declare: This clause initializes the cursor into memory.
Open: the previously declared cursor is now open and memory is allotted.
Fetch: The previously declared and opened cursor can now access data;
Close: The previously declared, opened, and fetched cursor is closed, which also releases
memory allocation.
STEP 6: Run the Pl/Sql code and execute the program
STEP 7: Stop the process.

Coding:

DECLARE
CURSOR cdet IS SELECT emp_name FROM emp;
lv_emp_name emp.emp_name%type;

BEGIN
OPEN cdet;

LOOP
FETCH g99_det INTO lv_emp_name;
IF g99_det%NOTFOUND
THEN
EXIT;
END IF;
Dbms_output.put_line(‘Employee Fetched:‘||lv_emp_name);
END LOOP;
Dbms_output.put_line(‘Total rows fetched is‘||g99_det%R0WCOUNT);
CLOSE g99_det;
END:
/
Employee Fetched:BBB
Employee Fetched:XXX
Employee Fetched:YYY
Total rows fetched is 3
Result:
Thus the above queries are executed successfully and output is verified.
4. Impement the concept of Stored procedure and function

Aim:
To write a program to implement the concept of Stored procedure and function
To create a bank database by creating two tables and writing stored procedures to
Find the net balance of the customer.

Algorithm:
STEP 1: Start the process.
STEP 2: Create two table for bankd and bank balwith attributes such as bank account number, customer
name, account type,credit,debit,balance.
STEP 3: Insert records into the table.
STEP 4: Create a function to calculate the net balance the return the net balance of the customer through
stored function
STEP 5: Use query using stored function to find net balance
STEP6:Stop the process

First Table creation


Create table bankd (bankaccnumber(10) primary key,namevarchar(20));
Table created

Second Table creation


Create table bankbal (balance number (5),bankacc number(10) references band(bankacc),branch
varchar(10),debit number(5),credit number(5));

Creating Function
Create or replace function calculate-netb (bankaccd number) return number is net number(10,2);
Begin
Net:=0;
Select (sum(balance)/100*5 into net frpombankbal from bankd where bankacc=bankaccd;
Return net;
End calculate-netb;
Function calling
Select bankd.name,sum(bal.balance) as netbalance,bal.credit,calculate-netb(1234567890)as net from
bankd,bankbalbalwherebankd.bankacc=1234567890 and bal.credit=10000
groupbybankd.name,bal.credit;

Output:
Name netbalance credit net
Rama 5000 1000 6050
CREATE [ORREPLACE] PROCEDURE PROCEDURENAME
[PARAMETER[IN/OUT/IN/IN OUT]
DATATYPE [:=/DEFAULT EXPRESSION]
[(PARAMET
ER)] IS/AS
DECLARATI
ON BEGIN
PL/SQL
CODES
[EXCEPTIO
N] END

Sample Output

*****FUCTION USING FOR STATEMENT*****

SQL>create or replace function fact(a number)return number as


2 inumber;
3 fnumber;
4 b
eg
in
5f:
=1
;
6 for i in 1..a
7 l
oo
p
8f:
=f*
i;
9 endloop;
10 retu
rn f;
11* end
fact;
SQL> /

Function created.
*********FUNCTION USING WHILE STATEMENT *************

SQL> create or replace function fact(a number) return number as


2 inumber;
3 fnumber;
4 begin
5 f:=1;
6 i:=1;
7 while (i<=a)
8 loop
9f:=f*i;
10 i:=i+1;
12 return f;
13* end fact;/
Function
created.

SQL>begin
2 dbms_output.put_line('the
factorial='||fact(&a)); 3* end;
SQL> /
Enter value for a: 4
old 2: dbms_output.put_line('the factorial='||fact(&a))
new 2: dbms_output.put_line('the factorial='||fact(4));
the factorial=24
PL/SQL procedure successfully completed.
*****PROCEDURE TO FIND WHETHER A GIVEN NUMBER IS ODD OR EVEN*********
SQL> declare
2 nnumber;
3 b
egin
4n:=
&n;
5 if(mod(n,2)=0)then
6 dbms_output.put_line(n||'iseven');
7 else
8 dbms_output.put_line(n||'isodd');
9 endif;
10 e
nd
;
11
/
Enter value for
n: 3 old 4:
n:=&n;
new 4:
n:=3; 3is
odd
PL/SQL procedure successfully completed.
*********PROCEDURE TO DISPLAY 1-10 USING WHILE*******
1 declare
2 nnumber;
3 inumber;
4 b
egin
5
n:=
10;
6i:=
7 while (i<=n)
8 loop
9 dbms_output.put_li
ne(i); 10i:=i+1;
11 end
loop;
12*end;
SQL> /
1
2
3
4
5
6
7
8
9
10

PL/SQL procedure successfully completed.


***********Procedure to display some numbers lesser than given number**********
declare
numnumber;
inumber;
begin
1 num:=&
num;
6i:=1;
7 loop
8 dbms_output.put_line(i);
9 exit
when(i>num);
10i:=i+1;
11 end
loop;
12* end;

SQL> /
Enter value for num:
4 old 5:
num:=&num;
new 5: num:=4;
1
2
3
4
5
PL/SQL procedure successfully completed.

RESULT:

Thus the functions and stored procedures are executed in SQL.


5. Database Trigger
AIM:
To perform High-level language extension with triggers (Student mark list).
Algorithm:
STEP 1: Start the process.
STEP 2: Create a table with student with the details about the students mark are being in the stu table with
attributes. Name, Rollno, Mark, Mark2, Mark3
STEP 3: Insert records into the table student.
STEP 4: The stu1 table consists of attributes, Rollno, Total, Average, Result
STEP 5: The details of the first table are being given in the prompt by the user. The total, average are processed
for currently processed row in the stu table using after insert on trigger the values are placed in the table stu1.
STEP 6: Select all the records and view the output.
STEP 7: Stop the process.

SYNTAX:
CREATE[OR REPLACE]TRIGGER[schema.]trigger
{BEFORE|AFTER|INSTEAD OF}
{DELETE
|INSERT
|UPDATE[OFcolumn[,column] ............................]}
|OR {DELETE
|INSERT
|UPDATE[OF column,[,column]....]}]...
ON[schema.]{table|view} REFERENCING(OLD[AS]old
|NEW[AS]new. ]
FOR EACH{ROW|STATEMENT}{WHEN(condition)}]
DESCRIPTION:
The details about the students mark are being in the stu table with attributes.
Name, Rollno, Mark, Mark2, Mark3.
The stu1 table consists of attributes, Rollno, Total, Average, Result
The details of the first table are being given in the prompt by the user. The total, average are processed for
currently processed row in the stu table using after insert on trigger the values are placed in the table stu1.
Trigger
Create or replace trigger strig
After insert on st1
For each
row
Declare
Total number(8);
Avg number(8);
Result
varchar2(20);
Begin
Total:=(:new.m1+:new.m2+:new.m3);
Avg:=total/3;
If(:new.m1>50 and :new.m2>50 and:new.m3>50) yhen
Result:=’pass’;
Else
Result:=’f
ail’; End
if;
Insert into st2 values(:new.rollno,total,avg,result);
End;
/
Trigger created

SQL>insert into st1


values(‘raja’,004,100,99,90) 1 row created
SQL>select * from st2;
ROLLNO TOTAL AVG RESULT
4 289 96 Pass
RESULT:

Thus the high-level language extension with triggers has been performed for generating the
students mark list.
6. Study of Open source Database NOSQL
A NoSQL originally referring to non SQL or non relational is a database that provides a mechanism for storage and retrieval
of data. This data is modeled in means other than the tabular relations used in relational databases. Such databases came into
existence in the late 1960s, but did not obtain the NoSQL moniker until a surge of popularity in the early twenty-first century.
NoSQL databases are used in real-time web applications and big data and their use are increasing over time. NoSQL systems
are also sometimes called Not only SQL to emphasize the fact that they may support SQL-like query languages.
Here are some of the better known open source data stores/models labeled as "NoSQL":

MongoDB - Document Store

Free-form key-value-like data store with good performance

 Powerful, expansive query model


 Usability rivals that of Redis
 Good for complex data storage needs.
 Production-quality sharding capabilities

Apache Hbase - Wide Column Store/Column Families

Built on top of Hadoop, which has functionality similar to Google's GFS and MapReduce systems

 Hadoop's HDFS provides a mechanism that reliably stores and organizes large amounts of data
 Random access performance is on par with MySQL
 Has a high performance Thrift gateway
 Cascading source and sink modules

Cassandra - Wide Column Store/Column Families


First developed by Facebook

 SuperColumns can turn a simple key-value architecture into an architecture that handles sorted lists, based on an
index specified by the user.
 Can scale from one node to several thousand nodes clustered in different data centers.
 Can be tuned for more consistency or availability
 Smooth node replacement if one goes down
 Cassandra is mainly consists of two systems: Google’s BigTable and Amazon’s Dynamo

Bigtable is a compressed, high performance, proprietary data storage system built on Google File System, Chubby
Lock Service, SSTable and a few other Google technologies. On May 6, 2015, a public version of Bigtable was made
available as a service.

Types of NoSQL database:


Types of NoSQL databases and the name of the databases system that falls in that category are:
1. MongoDB falls in the category of NoSQL document based database.
2. Key value store: Memcached, Redis, Coherence
3. Tabular: Hbase, Big Table, Accumulo
4. Document based: MongoDB, CouchDB, Cloudant

To start using MongoDb we use Putty -PuTTY is a free and open-source terminal emulator, serial console and network file
transfer application. It supports several network protocols, including SCP, SSH, Telnet, rlogin, and raw socket connection. It
can also connect to a serial port. The name "PuTTY" has no official meaning
https://www.putty.org/
PuTTY is an SSH and telnet client, developed originally by Simon Tatham for the Windows platform. PuTTY is open source
software that is available with source code and is developed and supported by a group of volunteers.
7. Design and Implement 5 Queries in Mongo DB.

Aim:
To design and implement 5 queries in Mongo DB
Algorithm:
STEP 1: Start the process.
STEP 2: Extract Zip File of putty server Setup for Windows OS.
STEP 3: Open command prompt. Set the path to bin directory of MongoDB. Putty
STEP 4: One can create a working DB directory using putty
STEP 5: Perform Queries in MongoDB
STEP 6: keep the server in running state.
STEP 7: Stop the process.

Coding:
show dbs
usemsc
db.msc.insert({“name”:”priya”})
show dbs
db.msc.find()
If you want to use a database with name <mydb>, then use DATABASE statement would be as follows

>use mydb
switched to db mydb
To check your currently selected database, use the command db
>db
mydb
If you want to check your databases list, use the command show dbs.
>show dbs
local 0.78125GB
test 0.23012GB
Your created database (mydb) is not present in list. To display database, you need to insert at least one
document into it.
>db.movie.insert({"name":"myclass"})
>show dbs
local 0.78125GB
mydb 0.23012GB
test 0.23012GB
In MongoDB default database is test. If you didn't create any database, then collections will be stored in
test database.
The dropDatabase() Method
MongoDB db.dropDatabase() command is used to drop a existing database.
Syntax
Basic syntax of dropDatabase() command is as follows −
db.dropDatabase()
This will delete the selected database. If you have not selected any database, then it will delete default
'test' database.

Example
First, check the list of available databases by using the command, show dbs.
>show dbs
local 0.78125GB
mydb 0.23012GB
test 0.23012GB
>
If you want to delete new database <mydb>, then dropDatabase() command would be as follows −
>use mydb
switched to db mydb
>db.dropDatabase()
>{ "dropped" : "mydb", "ok" : 1 }
>
Now check list of databases.
>show dbs
local 0.78125GB
test 0.23012GB
>

RESULT:
Thus the above queries are executed successfully and the output is verified.
8. Aggregation and indexing in Mongo DB.

Aim:
To design and implement aggregation and indexing in Mongo DB

Algorithm:
STEP 1: Start the process.
STEP 2: Extract Zip File of putty server Setup for Windows OS.
STEP 3: Open command prompt. Set the path to bin directory of MongoDB. Putty
STEP 4: One can create a working DB directory using putty
STEP 5: Perform Queries with index and sort by adding rows in MongoDB
STEP 6: keep the server in running state.
STEP 7: Stop the process.

Coding:
show dbs
use siva
db.siva.insert({“name”:”shiva”})
show dbs
db.siva.find()
db.siva.insert({“Place”:”Coimbatore ”})
db.siva.insert({“Place”:”Tirupur”})
db.siva.insert({“Place”:”Pollachi”})
db.siva.find().sort({“place”:-1})
db.siva.ensureindex({“place”:1})
>db.COLLECTION_NAME.find().sort({KEY:1})

Consider the collection myycol has the following data.


{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
Following example will display the documents sorted by title in the descending order.
>db.mycol.find({},{"title":1,_id:0}).sort({"title":-1})
{"title":"Tutorials Point Overview"}
{"title":"NoSQL Overview"}
{"title":"MongoDB Overview"}
>
Please note, if you don't specify the sorting preference, then sort() method will display the documents in
ascending order.
The basic syntax of ensureIndex() method is as follows().
>db.COLLECTION_NAME.ensureIndex({KEY:1})
Here key is the name of the field on which you want to create index and 1 is for ascending
order. To create index in descending order you need to use -1
>db.mycol.ensureIndex({"title":1})
>
In ensureIndex() method you can pass multiple fields, to create index on multiple fields.
>db.mycol.ensureIndex({"title":1,"description":-1})
>

RESULT:
Thus the above queries are executed successfully and the output is verified.
9. Database Application using Java and MongoDB as a back end

Aim:
To design a dababase application in MongoDB

Installation

Before you start using MongoDB in your Java programs, you need to make sure that you have
MongoDB JDBC driver and Java set up on the machine. You can check Java tutorial for Java
installation on your machine. Now, let us check how to set up MongoDB JDBC driver.
You need to download the jar from the path Download mongo.jar. Make sure to download the latest
release of it.
You need to include the mongo.jar into your classpath.
 To create a collection, createCollection() method of com.mongodb.client.MongoDatabase class
is used.

import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;

public class ConnectToDB {

public static void main( String args[] ) {

// Creating a Mongo client


MongoClient mongo = new MongoClient( "localhost" , 27017 );

// Creating Credentials
MongoCredential credential;
credential = MongoCredential.createCredential("sampleUser", "myDb",
"password".toCharArray());
System.out.println("Connected to the database successfully");

// Accessing the database


MongoDatabase database = mongo.getDatabase("myDb");
System.out.println("Credentials ::"+ credential);
}
}
$javac ConnectToDB.java
$java ConnectToDB
Connected to the database successfully
Credentials ::MongoCredential{
mechanism = null,
userName = 'sampleUser',
source = 'myDb',
password = <hidden>
mechanismProperties = {}
}
import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;

public class CreatingCollection {

public static void main( String args[] ) {

// Creating a Mongo client


MongoClient mongo = new MongoClient( "localhost" , 27017 );

// Creating Credentials
MongoCredential credential;
credential = MongoCredential.createCredential("sampleUser", "myDb",
"password".toCharArray());
System.out.println("Connected to the database successfully");

//Accessing the database


MongoDatabase database = mongo.getDatabase("myDb");

//Creating a collection
database.createCollection("sampleCollection");
System.out.println("Collection created successfully");
}
}
On compiling, the above program gives you the following result −
Connected to the database successfully
Collection created successfully

RESULT:
Thus the above queries are executed successfully and the output is verified.
10. JDBC with Database Connectivity
AIM:
To create a program using JDBC for creating a table of inserting records in java action.
ALGORITHM:
STEP1: Start the process.
STEP2: Import the java package like sql.
STEP3: Create a table with required fields.
STEP4: using query of insert the Value into the table.
STEP5: Connection with oracle the username and string should be entered.
STEP6: Create database , Start  control panel  Administrator odbc
STEP7: In microsoft oracle sql server give database username and host string.
STEP8: close the connection.
STEP9: Save and execute the file.
STEP10: stop the process.

Coding
import java.io.*;
import java.sql.*;
import java.util.*;
import java.lang.*;
class j2
{
public static void main(String args[])throws Exception,SQLException
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c=DriverManager.getConnection("jdbc:odbc:S");
Statement s=c.createStatement();
System.out.println("connected");
ResultSet rs;
s.executeUpdate("Insert into login values(1,'aishu')");
s.executeUpdate("Insert into login values(2,'abi')");
rs=s.executeQuery("Select * from login");
System.out.println("\n REGNO\t\tNAME");
while(rs.next())
{
int a=rs.getInt(1);
String b=rs.getString(2);
System.out.println(" "+a+"\t\t"+b);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output:

You might also like