SlideShare a Scribd company logo
1 of 27
Download to read offline
Advances in Database Management Systems Laboratory Work 2014-2015
1
PROGRAM 1.
Develop a database application to demonstrate storing and retrieving of BLOB and
CLOB object.
Theory:-
CLOB stands for Character Large Object. It is a datatype used to store and retrieve
large amount of text data in character format. CLOB datatypes are created by using
CREATE commands. It can store Single byte and multiple byte character data. It
supports both fixed width and variable width character set.
A CLOB contains a logical pointer to a CLOB, not the CLOB itself. CLOB columns
are referred as LONG VARCHAR.
BLOB stands for Binary Large object or Basic Large Object. It is a datatype used to
store unstructured binary large objects. It is an array of bytes(byte[]) stored in the
database. It is not case sensitive Blob’s are used to hold multimedia objects.
BLOB’s fields are normally used to store graphics, audio, video, still images and so
on.
Insertb.java
Packagevemana;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.IOException;
importjava.io.PrintWriter;
importjava.sql.Connection;
importjava.sql.DriverManager;
importjava.sql.PreparedStatement;
importjava.sql.SQLException;
importjava.util.logging.Level;
importjava.util.logging.Logger;
Advances in Database Management Systems Laboratory Work 2014-2015
2
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
public class insertb extends HttpServlet {
protected void doGet (HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException {
FileInputStream is = null;
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
// Connect to Oracle
out.println("<html>");
out.println("<body>");
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe"
, "hr", "hr");
PreparedStatementps = con.prepareStatement("insert into pic values(?,?,?)
");
ps.setInt(1,3);
ps.setString(2,"Java Logo");
File fBlob = new File
("C:UsersinsbinsDocumentsNetBeansProjectsBLOBCLOBTrialsr
cjavavemanaJellyfish.jpg");
is = new FileInputStream ( fBlob );
ps.setBinaryStream (3, is, (int) fBlob.length() );
ps.executeUpdate();
if (is != null)
is.close();
out.println("Image sucessfully inserted into database");
out.println("</body>");
Advances in Database Management Systems Laboratory Work 2014-2015
3
out.println("</html>");
}
catch(Exception e)
{
System.out.println(e);
}
finally {
out.close();
}
}
}
GetBLOB.java
packagevemana;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.OutputStream;
importjava.sql.Blob;
importjava.sql.Connection;
importjava.sql.DriverManager;
importjava.sql.PreparedStatement;
importjava.sql.ResultSet;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
public class GetBLOB extends HttpServlet
{
protected void processRequest (HttpServletRequest request, HttpServletResponse
response)
throwsServletException, IOException
{
Advances in Database Management Systems Laboratory Work 2014-2015
4
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connectioncon=DriverManager.getConnection("jdbc:oracle:thin:@localho
st:1521:xe", "hr", "hr");
PreparedStatementps = con.prepareStatement("select image from pic
where id = ?");
String id = request.getParameter("id");
ps.setString(1,id);
ResultSetrs = ps.executeQuery();
rs.next();
Blob b = rs.getBlob("image");
response.setContentType("image/jpeg");
response.setContentLength( (int) b.length());
InputStream is = b.getBinaryStream();
OutputStreamos = response.getOutputStream();
bytebuf[] = new byte[(int) b.length()];
is.read(buf);
os.write(buf);
os.close();
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException
{
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponseresponse)
throwsServletException, IOException
{
Advances in Database Management Systems Laboratory Work 2014-2015
5
processRequest(request, response);
}
Bdisplay.java
packagevemana;
importjava.io.IOException;
importjava.io.PrintWriter;
importjava.sql.Connection;
importjava.sql.DriverManager;
importjava.sql.PreparedStatement;
importjava.sql.ResultSet;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
public class bdisplay extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException
{
String id;
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try
{
out.println("<html>");
out.println("<body>");
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe",
"hr", "hr");
PreparedStatementps = con.prepareStatement("select * from pic");
ResultSetrs = ps.executeQuery();
out.println("<h1>Photos</h1>");
Advances in Database Management Systems Laboratory Work 2014-2015
6
while ( rs.next())
{
id=rs.getString("id");
out.println("<h4>" +id+ "</h4>");
out.println("<img width='160' height='160'
src=GetBLOB?id="+id+"></img><p/>");
}
out.println("</body>");
out.println("</html>");
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
out.close();
}
}
}
Steps for storing and retrieving of BLOB and CLOB object:
Step 1: Connect to Oracle JDBC driver.
Step 2: Creating a BLOB.
Step 3: Inserting image into a BLOB.
Step 4: Querying a database for a BLOB.
Step 5: Executing a binary data.
Step 6: Storing and Retrieving of BLOB and CLOB object was displayed
successfully.
Advances in Database Management Systems Laboratory Work 2014-2015
7
OUTPUT:
Advances in Database Management Systems Laboratory Work 2014-2015
8
CONCLUSION: - An application for storing and retrieving of BLOB and CLOB object
wasimplemented successfully.
Advances in Database Management Systems Laboratory Work 2014-2015
9
PROGRAM 2.
Develop a database application to demonstrate the representation of multivalued
attributes, and use of nested tables to represent complex objects. Write suitable
queries to demonstrate it.
Theory:-
Nested table is an Oracle data type used to support columns containing multivalued
attributes, in this case, columns that can hold an entire sub-table.
Example:
Create a table with NESTED TABLE column:
SQL>CREATE TYPE my_tab_t AS TABLE OF VARCHAR2(30);
Output:
Type Created.
SQL >CREATE TABLE nested_table (id NUMBER, col1 my_tab_v)
NESTED TABLE col1 STORE AS col1_tab;
Output:
Table created.
Inserting data into table:
SQL >INSERT INTO nested_table VALUES (1, my_tab_v('A'));
1 row created.
SQL >INSERT INTO nested_table VALUES (2, my_tab_v('B', 'C'));
1 row created.
SQL >INSERT INTO nested_table VALUES (3, my_tab_v('D', 'E', 'F'));
1 row created.
SQL >COMMIT;
Commit complete.
Advances in Database Management Systems Laboratory Work 2014-2015
10
Selecting from nested table:
SQL >SELECT * FROM nested_table;
Output:
ID COL1
1 MY_TAB_V('A')
2 MY_TAB_V('B', 'C')
3 MY_TAB_V('D', 'E', 'F')
SQL >SELECT id, COLUMN_VALUE FROM nested_table t1, TABLE(t1.col1) t2;
Output:
ID ID COLUMN_VALUE
1 A
2 B
2 C
3 D
3 E
3 F
6 rows selected.
Conclusion: - Application to demonstrate the representation of multivalued attributes,
and use of nested tables to represent complex objects was successfully executed with the
help of above queries.
Advances in Database Management Systems Laboratory Work 2014-2015
11
PROGRAM 3.
Design and develop a suitable student database application .one of the attributes to
be maintained is the attendance of a student in each subject for which he/she has
enrolled. Using TRIGGERS, write active rules to do the following
a) Whenever the attendance is updated, check if the attendance is less than 85%, if
so notify the head of the department concerned.
b) Whenever the marks in an internal assessment test are entered, check if the
marks is less than 40%, if, so notify the head of the department concerned.
create table stud_rec(regno varchar(10) primary key,name varchar2(10) not null,major
varchar2(10),mark number(4),attendence number(4));
Table created.
SQL> desc stud_rec;
Name Null? Type
REGNO NOT NULL VARCHAR2(10)
NAME NOT NULL VARCHAR2(10)
MARKS VARCHAR2(10)
MAJOR NUMBER(4)
ATTENDENCE NUMBER(4)
SQL> insert into stud_rec values('&regno','&name','&major',&mark,&atttendance);
Enter value for regno: 001
Enter value for name: pinky
Enter value for major: cse
Enter value for mark: 85
Enter value for atttendance: 70
old 1: insert into stud_rec values('&regno','&name','&major',&mark, &atttendance)
new 1: insert into stud_rec values('001','pinky','cse',85,70)
1 row created.
SQL> /
Enter value for regno: 002
Enter value for name: john
Enter value for major: cse
Enter value for mark: 30
Advances in Database Management Systems Laboratory Work 2014-2015
12
Enter value for atttendance: 70
old 1: insert into stud_rec values('&regno','&name','&major',&mark,&atttendance)
new 1: insert into stud_rec values('002','john','cse',30,70)
1 row created.
SQL> /
Enter value for regno: 003
Enter value for name: arun
Enter value for major: cse
Enter value for mark: 90
Enter value for atttendance: 95
old 1: insert into stud_rec values('&regno','&name','&major',&mark,&atttendance)
new 1: insert into stud_rec values('003','arun','cse',90,95)
1 row created.
SQL> select * from stud_rec;
REGNO NAME MARKS MAJOR ATTENDENCE
001 pinky cse 85 70
002 john cse 30 70
003 arun cse 90 95
create TRIGGER trig_attee_mark after update on stud_rec
for each row
begin
if ( :new.attendence < 85 ) then dbms_output.put_line (:new.name || ' bearing REG.NO. '||
:new.regno || ' has attendence less than 85 ' );
end if;
if ( :new.mark < 40 ) then dbms_output.put_line (:new.name || ' bearing REG.NO. '||
:new.regno || ' got mark less than 40 ' );
end if;
end;
Trigger created.
SQL> select * from stud_rec;
REGNO NAME MARKS MAJOR ATTENDENCE
001 pinky cse 85 70
Advances in Database Management Systems Laboratory Work 2014-2015
13
002 john cse 30 70
003 arun cse 90 95
SQL> update stud_rec set attendence=25 where regno='001';
1 row updated.
SQL> select * from stud_rec;
REGNO NAME MARKS MAJOR ATTENDENCE
001 pinky cse 85 25
002 john cse 30 70
003 arun cse 90 95
Advances in Database Management Systems Laboratory Work 2014-2015
14
PROGRAM 4.
Design, develop and execute a program in a language of your choice to implement
any one algorithm for mining association rules. Run the program against any large
database available in the public domain and discuss the results.
Theory:-
Apriori is a classic algorithm for frequent itemset mining and association rule learning
over transactional databases. It proceeds by identifying the frequent individual items in
the database and extending them to larger and larger item sets as long as those item sets
appear sufficiently often in the database. The frequent item sets determined by Apriori
can be used to determine association rules which highlight general trends in the database:
this has applications in domains such as market basket analysis.
Steps in execution:
STEP 1: Create two notepad files and name them config.txt and transa.txt respectively.
STEP 2: In config.txt file, insert 3 lines of input
line 1 - number of items per transaction
line 2 - number of transactions
line 3 –minsup
STEP 3: In transa.txt file, which is the transaction file, where the input is separated by
space.
STEP 4: These two input files belongs to the class AprioriCalculation.Copy these two
input files in the specified path
STEP 5: Run the program in netbeans.
Advances in Database Management Systems Laboratory Work 2014-2015
15
package apriori;
import java.io.*;
import java.util.*;
public class Apriori {
public static void main(String[] args) {
AprioriCalculationap = new AprioriCalculation();
ap.aprioriProcess();
}
}
/***************************************************************
* Class Name : AprioriCalculation
* Purpose : generate Aprioriitemsets
***************************************************************/
class AprioriCalculation
{
Vector<String> candidates=new Vector<String>(); //the current candidates
String configFile="config.txt"; //configuration file
String transaFile="transa.txt"; //transaction file
String outputFile="apriori-output.txt";//output file
intnumItems; //number of items per transaction
intnumTransactions; //number of transactions
double minSup; //minimum support for a frequent itemset
String oneVal[]; //array of value per column that will be treated as a '1'
String itemSep = " "; //the separator value for items in the database
Advances in Database Management Systems Laboratory Work 2014-2015
16
/***************************************************************
* Method Name : aprioriProcess
* Purpose : Generate the aprioriitemsets
* Parameters : None
* Return : None
***************************************************************/
public void aprioriProcess()
{
Date d; //date object for timing purposes
long start, end; //start and end time
intitemsetNumber=0; //the current itemset being looked at
//get config
getConfig();
System.out.println("Apriori algorithm has started.n");
//start timer
d = new Date();
start = d.getTime();
//while not complete
do
{
//increase the itemset that is being looked at
itemsetNumber++;
//generate the candidates
generateCandidates(itemsetNumber);
//determine and display frequent itemsets
calculateFrequentItemsets(itemsetNumber);
if(candidates.size()!=0)
{
System.out.println("Frequent " + itemsetNumber + "-itemsets");
Advances in Database Management Systems Laboratory Work 2014-2015
17
System.out.println(candidates);
}
//if there are <=1 frequent items, then its the end. This prevents reading through the
database again. When there is only one frequent itemset.
}while(candidates.size()>1);
//end timer
d = new Date();
end = d.getTime();
//display the execution time
System.out.println("Execution time is: "+((double)(end-start)/1000) + " seconds.");
}
/***************************************************************
* Method Name : getInput
* Purpose : get user input from System.in
* Parameters : None
* Return : String value of the users input
***************************************************************/
public static String getInput()
{
String input="";
//read from System.in
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
//try to get users input, if there is an error print the message
try
{
input = reader.readLine();
}
catch (Exception e)
{
System.out.println(e);
Advances in Database Management Systems Laboratory Work 2014-2015
18
}
return input;
}
/***************************************************************
* Method Name : getConfig
* Purpose : get the configuration information (config filename, transaction
filename)
*: configFile and transaFile will be change appropriately
* Parameters : None
* Return : None
***************************************************************/
private void getConfig()
{
FileWriterfw;
BufferedWriterfile_out;
String input="";
//ask if want to change the config
System.out.println("Default Configuration: ");
System.out.println("tRegular transaction file with '" + itemSep + "' item
separator.");
System.out.println("tConfig File: " + configFile);
System.out.println("tTransa File: " + transaFile);
System.out.println("tOutput File: " + outputFile);
System.out.println("nPress 'C' to change the item separator, configuration file and
transaction files");
System.out.print("or any other key to continue. ");
input=getInput();
if(input.compareToIgnoreCase("c")==0)
{
System.out.print("Enter new transaction filename (return for '"+transaFile+"'): ");
input=getInput();
Advances in Database Management Systems Laboratory Work 2014-2015
19
if(input.compareToIgnoreCase("")!=0)
transaFile=input;
System.out.print("Enter new configuration filename (return for '"+configFile+"'):
");
input=getInput();
if(input.compareToIgnoreCase("")!=0)
configFile=input;
System.out.print("Enter new output filename (return for '"+outputFile+"'): ");
input=getInput();
if(input.compareToIgnoreCase("")!=0)
outputFile=input;
System.out.println("Filenames changed");
System.out.print("Enter the separating character(s) for items (return for
'"+itemSep+"'): ");
input=getInput();
if(input.compareToIgnoreCase("")!=0)
itemSep=input;
}
try
{
FileInputStreamfile_in = new FileInputStream(configFile);
BufferedReaderdata_in = new BufferedReader(new InputStreamReader(file_in));
//number of items
numItems=Integer.valueOf(data_in.readLine()).intValue();
//number of transactions
numTransactions=Integer.valueOf(data_in.readLine()).intValue();
//minsup
minSup=(Double.valueOf(data_in.readLine()).doubleValue());
Advances in Database Management Systems Laboratory Work 2014-2015
20
//output config info to the user
System.out.print("nInput configuration: "+numItems+" items,
"+numTransactions+" transactions, ");
System.out.println("minsup = "+minSup+"%");
System.out.println();
minSup/=100.0;
oneVal = new String[numItems];
System.out.print("Enter 'y' to change the value each row recognizes as a '1':");
if(getInput().compareToIgnoreCase("y")==0)
{
for(inti=0; i<oneVal.length; i++)
{
System.out.print("Enter value for column #" + (i+1) + ": ");
oneVal[i] = getInput();
}
}
else
for(inti=0; i<oneVal.length; i++)
oneVal[i]="1";
//create the output file
fw= new FileWriter(outputFile);
file_out = new BufferedWriter(fw);
//put the number of transactions into the output file
file_out.write(numTransactions + "n");
file_out.write(numItems + "n******n");
file_out.close();
}
//if there is an error, print the message
catch(IOException e)
{
Advances in Database Management Systems Laboratory Work 2014-2015
21
System.out.println(e);
}
}
/***************************************************************
* Method Name : generateCandidates
* Purpose : Generate all possible candidates for the n-thitemsets
* : these candidates are stored in the candidates class vector
* Parameters : n - integer value representing the current itemsets to be created
* Return : None
***************************************************************/
private void generateCandidates(int n)
{
Vector<String>tempCandidates = new Vector<String>(); //temporary candidate
string vector
String str1, str2; //strings that will be used for comparisons
StringTokenizer st1, st2; //string tokenizers for the two itemsets being compared
//if its the first set, candidates are just the numbers
if(n==1)
{
for(inti=1; i<=numItems; i++)
{
tempCandidates.add(Integer.toString(i));
}
}
else if(n==2) //second itemset is just all combinations of itemset 1
{
//add each itemset from the previous frequent itemsets together
for(inti=0; i<candidates.size(); i++)
{
st1 = new StringTokenizer(candidates.get(i));
str1 = st1.nextToken();
for(int j=i+1; j<candidates.size(); j++)
{
Advances in Database Management Systems Laboratory Work 2014-2015
22
st2 = new StringTokenizer(candidates.elementAt(j));
str2 = st2.nextToken();
tempCandidates.add(str1 + " " + str2);
}
}
}
else
{
//for each itemset
for(inti=0; i<candidates.size(); i++)
{
//compare to the next itemset
for(int j=i+1; j<candidates.size(); j++)
{
//create the strigns
str1 = new String();
str2 = new String();
//create the tokenizers
st1 = new StringTokenizer(candidates.get(i));
st2 = new StringTokenizer(candidates.get(j));
//make a string of the first n-2 tokens of the strings
for(int s=0; s<n-2; s++)
{
str1 = str1 + " " + st1.nextToken();
str2 = str2 + " " + st2.nextToken();
}
//if they have the same n-2 tokens, add them together
if(str2.compareToIgnoreCase(str1)==0)
tempCandidates.add((str1 + " " + st1.nextToken() + " " +
st2.nextToken()).trim());
}
}
Advances in Database Management Systems Laboratory Work 2014-2015
23
}
//clear the old candidates
candidates.clear();
//set the new ones
candidates = new Vector<String>(tempCandidates);
tempCandidates.clear();
}
/***************************************************************
* Method Name : calculateFrequentItemsets
* Purpose : Determine which candidates are frequent in the n-thitemsets
* from all possible candidates
* Parameters : n - iteger representing the current itemsets being evaluated
***************************************************************/
private void calculateFrequentItemsets(int n)
{
Vector<String>frequentCandidates = new Vector<String>(); //the frequent
candidates for the current itemset
FileInputStreamfile_in; //file input stream
BufferedReaderdata_in; //data input stream
FileWriterfw;
BufferedWriterfile_out;
StringTokenizerst, stFile; //tokenizer for candidate and transaction
boolean match; //whether the transaction has all the items in an itemset
boolean trans[] = new boolean[numItems]; //array to hold a transaction so that can be
checked
int count[] = new int[candidates.size()]; //the number of successful matches
try
{
//output file
fw= new FileWriter(outputFile, true);
file_out = new BufferedWriter(fw);
//load the transaction file
Advances in Database Management Systems Laboratory Work 2014-2015
24
file_in = new FileInputStream(transaFile);
data_in = new BufferedReader(new InputStreamReader(file_in));
//for each transaction
for(inti=0; i<numTransactions; i++)
{
//System.out.println("Got here " + i + " times"); //useful to debug files that
you are unsure of the number of line
stFile = new StringTokenizer(data_in.readLine(), itemSep); //read a line from
the file to the tokenizer
//put the contents of that line into the transaction array
for(int j=0; j<numItems; j++)
{
trans[j]=(stFile.nextToken().compareToIgnoreCase(oneVal[j])==0); //if it
is not a 0, assign the value to true
}
//check each candidate
for(int c=0; c<candidates.size(); c++)
{
match = false; //reset match to false
//tokenize the candidate so that we know what items need to be present for
a match
st = new StringTokenizer(candidates.get(c));
//check each item in the itemset to see if it is present in the transaction
while(st.hasMoreTokens())
{
match = (trans[Integer.valueOf(st.nextToken())-1]);
if(!match) //if it is not present in the transaction stop checking
break;
}
if(match) //if at this point it is a match, increase the count
count[c]++;
}
Advances in Database Management Systems Laboratory Work 2014-2015
25
}
for(inti=0; i<candidates.size(); i++)
{
// System.out.println("Candidate: " + candidates.get(c) + " with count: " +
count + " % is: " + (count/(double)numItems));
//if the count% is larger than the minSup%, add to the candidate to the
frequent candidates
if((count[i]/(double)numTransactions)>=minSup)
{
frequentCandidates.add(candidates.get(i));
//put the frequent itemset into the output file
file_out.write(candidates.get(i) + "," + count[i]/(double)numTransactions +
"n");
}
}
file_out.write("-n");
file_out.close();
}
//if error at all in this process, catch it and print the error messate
catch(IOException e)
{
System.out.println(e);
}
//clear old candidates
candidates.clear();
//new candidates are the old frequent candidates
candidates = new Vector<String>(frequentCandidates);
frequentCandidates.clear();
}
}
Advances in Database Management Systems Laboratory Work 2014-2015
26
Input:
Advances in Database Management Systems Laboratory Work 2014-2015
27
Output:-

More Related Content

What's hot (20)

Ms sql-server
Ms sql-serverMs sql-server
Ms sql-server
 
Sql commands
Sql commandsSql commands
Sql commands
 
SQL Overview
SQL OverviewSQL Overview
SQL Overview
 
Dbms lab Manual
Dbms lab ManualDbms lab Manual
Dbms lab Manual
 
Arrays
ArraysArrays
Arrays
 
The Basics of MongoDB
The Basics of MongoDBThe Basics of MongoDB
The Basics of MongoDB
 
SQL Functions
SQL FunctionsSQL Functions
SQL Functions
 
1 - Introduction to PL/SQL
1 - Introduction to PL/SQL1 - Introduction to PL/SQL
1 - Introduction to PL/SQL
 
Working with Databases and MySQL
Working with Databases and MySQLWorking with Databases and MySQL
Working with Databases and MySQL
 
Python-Inheritance.pptx
Python-Inheritance.pptxPython-Inheritance.pptx
Python-Inheritance.pptx
 
Aggregate function
Aggregate functionAggregate function
Aggregate function
 
03 Linear Arrays Memory Representations .pdf
03 Linear Arrays Memory Representations .pdf03 Linear Arrays Memory Representations .pdf
03 Linear Arrays Memory Representations .pdf
 
Command line arguments.21
Command line arguments.21Command line arguments.21
Command line arguments.21
 
Nested Queries Lecture
Nested Queries LectureNested Queries Lecture
Nested Queries Lecture
 
MongoDB presentation
MongoDB presentationMongoDB presentation
MongoDB presentation
 
Sql ppt
Sql pptSql ppt
Sql ppt
 
Dom
DomDom
Dom
 
2- Dimensional Arrays
2- Dimensional Arrays2- Dimensional Arrays
2- Dimensional Arrays
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQL
 
SQL commands
SQL commandsSQL commands
SQL commands
 

Similar to M.TECH 1ST SEM COMPUTER SCIENCE ADBMS LAB PROGRAMS

Local storage in Web apps
Local storage in Web appsLocal storage in Web apps
Local storage in Web appsIvano Malavolta
 
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...TAISEEREISA
 
Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...
Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...
Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...NoSQLmatters
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile appsIvano Malavolta
 
Data Warehouse and Business Intelligence - Recipe 3
Data Warehouse and Business Intelligence - Recipe 3Data Warehouse and Business Intelligence - Recipe 3
Data Warehouse and Business Intelligence - Recipe 3Massimo Cenci
 
Advanced SQL - Database Access from Programming Languages
Advanced SQL - Database Access  from Programming LanguagesAdvanced SQL - Database Access  from Programming Languages
Advanced SQL - Database Access from Programming LanguagesS.Shayan Daneshvar
 
MySQL New Features -- Sunshine PHP 2020 Presentation
MySQL New Features -- Sunshine PHP 2020 PresentationMySQL New Features -- Sunshine PHP 2020 Presentation
MySQL New Features -- Sunshine PHP 2020 PresentationDave Stokes
 
Why re-use core classes?
Why re-use core classes?Why re-use core classes?
Why re-use core classes?Levi Waldron
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursorsinfo_zybotech
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursorsinfo_zybotech
 
Fast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleFast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleRaimonds Simanovskis
 
Android database tutorial
Android database tutorialAndroid database tutorial
Android database tutorialinfo_zybotech
 
Viastudy ef core_cheat_sheet
Viastudy ef core_cheat_sheetViastudy ef core_cheat_sheet
Viastudy ef core_cheat_sheetimdurgesh
 
ShmooCon 2009 - (Re)Playing(Blind)Sql
ShmooCon 2009 - (Re)Playing(Blind)SqlShmooCon 2009 - (Re)Playing(Blind)Sql
ShmooCon 2009 - (Re)Playing(Blind)SqlChema Alonso
 
Oracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAsOracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAsAlex Zaballa
 
Oracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c  - New Features for Developers and DBAsOracle Database 12c  - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAsAlex Zaballa
 

Similar to M.TECH 1ST SEM COMPUTER SCIENCE ADBMS LAB PROGRAMS (20)

Local storage in Web apps
Local storage in Web appsLocal storage in Web apps
Local storage in Web apps
 
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
 
Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...
Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...
Simon Elliston Ball – When to NoSQL and When to Know SQL - NoSQL matters Barc...
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile apps
 
Sql lite android
Sql lite androidSql lite android
Sql lite android
 
Data Warehouse and Business Intelligence - Recipe 3
Data Warehouse and Business Intelligence - Recipe 3Data Warehouse and Business Intelligence - Recipe 3
Data Warehouse and Business Intelligence - Recipe 3
 
Advanced SQL - Database Access from Programming Languages
Advanced SQL - Database Access  from Programming LanguagesAdvanced SQL - Database Access  from Programming Languages
Advanced SQL - Database Access from Programming Languages
 
MySQL New Features -- Sunshine PHP 2020 Presentation
MySQL New Features -- Sunshine PHP 2020 PresentationMySQL New Features -- Sunshine PHP 2020 Presentation
MySQL New Features -- Sunshine PHP 2020 Presentation
 
Html web sql database
Html web sql databaseHtml web sql database
Html web sql database
 
Sql wksht-2
Sql wksht-2Sql wksht-2
Sql wksht-2
 
Why re-use core classes?
Why re-use core classes?Why re-use core classes?
Why re-use core classes?
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
 
Fast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleFast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on Oracle
 
Android database tutorial
Android database tutorialAndroid database tutorial
Android database tutorial
 
Viastudy ef core_cheat_sheet
Viastudy ef core_cheat_sheetViastudy ef core_cheat_sheet
Viastudy ef core_cheat_sheet
 
Sqlapi0.1
Sqlapi0.1Sqlapi0.1
Sqlapi0.1
 
ShmooCon 2009 - (Re)Playing(Blind)Sql
ShmooCon 2009 - (Re)Playing(Blind)SqlShmooCon 2009 - (Re)Playing(Blind)Sql
ShmooCon 2009 - (Re)Playing(Blind)Sql
 
Oracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAsOracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAs
 
Oracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c  - New Features for Developers and DBAsOracle Database 12c  - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAs
 

Recently uploaded

Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 

Recently uploaded (20)

Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 

M.TECH 1ST SEM COMPUTER SCIENCE ADBMS LAB PROGRAMS

  • 1. Advances in Database Management Systems Laboratory Work 2014-2015 1 PROGRAM 1. Develop a database application to demonstrate storing and retrieving of BLOB and CLOB object. Theory:- CLOB stands for Character Large Object. It is a datatype used to store and retrieve large amount of text data in character format. CLOB datatypes are created by using CREATE commands. It can store Single byte and multiple byte character data. It supports both fixed width and variable width character set. A CLOB contains a logical pointer to a CLOB, not the CLOB itself. CLOB columns are referred as LONG VARCHAR. BLOB stands for Binary Large object or Basic Large Object. It is a datatype used to store unstructured binary large objects. It is an array of bytes(byte[]) stored in the database. It is not case sensitive Blob’s are used to hold multimedia objects. BLOB’s fields are normally used to store graphics, audio, video, still images and so on. Insertb.java Packagevemana; importjava.io.File; importjava.io.FileInputStream; importjava.io.IOException; importjava.io.PrintWriter; importjava.sql.Connection; importjava.sql.DriverManager; importjava.sql.PreparedStatement; importjava.sql.SQLException; importjava.util.logging.Level; importjava.util.logging.Logger;
  • 2. Advances in Database Management Systems Laboratory Work 2014-2015 2 importjavax.servlet.ServletException; importjavax.servlet.http.HttpServlet; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; public class insertb extends HttpServlet { protected void doGet (HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException { FileInputStream is = null; response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { // Connect to Oracle out.println("<html>"); out.println("<body>"); Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe" , "hr", "hr"); PreparedStatementps = con.prepareStatement("insert into pic values(?,?,?) "); ps.setInt(1,3); ps.setString(2,"Java Logo"); File fBlob = new File ("C:UsersinsbinsDocumentsNetBeansProjectsBLOBCLOBTrialsr cjavavemanaJellyfish.jpg"); is = new FileInputStream ( fBlob ); ps.setBinaryStream (3, is, (int) fBlob.length() ); ps.executeUpdate(); if (is != null) is.close(); out.println("Image sucessfully inserted into database"); out.println("</body>");
  • 3. Advances in Database Management Systems Laboratory Work 2014-2015 3 out.println("</html>"); } catch(Exception e) { System.out.println(e); } finally { out.close(); } } } GetBLOB.java packagevemana; importjava.io.IOException; importjava.io.InputStream; importjava.io.OutputStream; importjava.sql.Blob; importjava.sql.Connection; importjava.sql.DriverManager; importjava.sql.PreparedStatement; importjava.sql.ResultSet; importjavax.servlet.ServletException; importjavax.servlet.http.HttpServlet; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; public class GetBLOB extends HttpServlet { protected void processRequest (HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {
  • 4. Advances in Database Management Systems Laboratory Work 2014-2015 4 try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connectioncon=DriverManager.getConnection("jdbc:oracle:thin:@localho st:1521:xe", "hr", "hr"); PreparedStatementps = con.prepareStatement("select image from pic where id = ?"); String id = request.getParameter("id"); ps.setString(1,id); ResultSetrs = ps.executeQuery(); rs.next(); Blob b = rs.getBlob("image"); response.setContentType("image/jpeg"); response.setContentLength( (int) b.length()); InputStream is = b.getBinaryStream(); OutputStreamos = response.getOutputStream(); bytebuf[] = new byte[(int) b.length()]; is.read(buf); os.write(buf); os.close(); } catch(Exception ex) { System.out.println(ex.getMessage()); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException { processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponseresponse) throwsServletException, IOException {
  • 5. Advances in Database Management Systems Laboratory Work 2014-2015 5 processRequest(request, response); } Bdisplay.java packagevemana; importjava.io.IOException; importjava.io.PrintWriter; importjava.sql.Connection; importjava.sql.DriverManager; importjava.sql.PreparedStatement; importjava.sql.ResultSet; importjavax.servlet.ServletException; importjavax.servlet.http.HttpServlet; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; public class bdisplay extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException { String id; response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { out.println("<html>"); out.println("<body>"); Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "hr", "hr"); PreparedStatementps = con.prepareStatement("select * from pic"); ResultSetrs = ps.executeQuery(); out.println("<h1>Photos</h1>");
  • 6. Advances in Database Management Systems Laboratory Work 2014-2015 6 while ( rs.next()) { id=rs.getString("id"); out.println("<h4>" +id+ "</h4>"); out.println("<img width='160' height='160' src=GetBLOB?id="+id+"></img><p/>"); } out.println("</body>"); out.println("</html>"); con.close(); } catch(Exception e) { System.out.println(e); } finally { out.close(); } } } Steps for storing and retrieving of BLOB and CLOB object: Step 1: Connect to Oracle JDBC driver. Step 2: Creating a BLOB. Step 3: Inserting image into a BLOB. Step 4: Querying a database for a BLOB. Step 5: Executing a binary data. Step 6: Storing and Retrieving of BLOB and CLOB object was displayed successfully.
  • 7. Advances in Database Management Systems Laboratory Work 2014-2015 7 OUTPUT:
  • 8. Advances in Database Management Systems Laboratory Work 2014-2015 8 CONCLUSION: - An application for storing and retrieving of BLOB and CLOB object wasimplemented successfully.
  • 9. Advances in Database Management Systems Laboratory Work 2014-2015 9 PROGRAM 2. Develop a database application to demonstrate the representation of multivalued attributes, and use of nested tables to represent complex objects. Write suitable queries to demonstrate it. Theory:- Nested table is an Oracle data type used to support columns containing multivalued attributes, in this case, columns that can hold an entire sub-table. Example: Create a table with NESTED TABLE column: SQL>CREATE TYPE my_tab_t AS TABLE OF VARCHAR2(30); Output: Type Created. SQL >CREATE TABLE nested_table (id NUMBER, col1 my_tab_v) NESTED TABLE col1 STORE AS col1_tab; Output: Table created. Inserting data into table: SQL >INSERT INTO nested_table VALUES (1, my_tab_v('A')); 1 row created. SQL >INSERT INTO nested_table VALUES (2, my_tab_v('B', 'C')); 1 row created. SQL >INSERT INTO nested_table VALUES (3, my_tab_v('D', 'E', 'F')); 1 row created. SQL >COMMIT; Commit complete.
  • 10. Advances in Database Management Systems Laboratory Work 2014-2015 10 Selecting from nested table: SQL >SELECT * FROM nested_table; Output: ID COL1 1 MY_TAB_V('A') 2 MY_TAB_V('B', 'C') 3 MY_TAB_V('D', 'E', 'F') SQL >SELECT id, COLUMN_VALUE FROM nested_table t1, TABLE(t1.col1) t2; Output: ID ID COLUMN_VALUE 1 A 2 B 2 C 3 D 3 E 3 F 6 rows selected. Conclusion: - Application to demonstrate the representation of multivalued attributes, and use of nested tables to represent complex objects was successfully executed with the help of above queries.
  • 11. Advances in Database Management Systems Laboratory Work 2014-2015 11 PROGRAM 3. Design and develop a suitable student database application .one of the attributes to be maintained is the attendance of a student in each subject for which he/she has enrolled. Using TRIGGERS, write active rules to do the following a) Whenever the attendance is updated, check if the attendance is less than 85%, if so notify the head of the department concerned. b) Whenever the marks in an internal assessment test are entered, check if the marks is less than 40%, if, so notify the head of the department concerned. create table stud_rec(regno varchar(10) primary key,name varchar2(10) not null,major varchar2(10),mark number(4),attendence number(4)); Table created. SQL> desc stud_rec; Name Null? Type REGNO NOT NULL VARCHAR2(10) NAME NOT NULL VARCHAR2(10) MARKS VARCHAR2(10) MAJOR NUMBER(4) ATTENDENCE NUMBER(4) SQL> insert into stud_rec values('&regno','&name','&major',&mark,&atttendance); Enter value for regno: 001 Enter value for name: pinky Enter value for major: cse Enter value for mark: 85 Enter value for atttendance: 70 old 1: insert into stud_rec values('&regno','&name','&major',&mark, &atttendance) new 1: insert into stud_rec values('001','pinky','cse',85,70) 1 row created. SQL> / Enter value for regno: 002 Enter value for name: john Enter value for major: cse Enter value for mark: 30
  • 12. Advances in Database Management Systems Laboratory Work 2014-2015 12 Enter value for atttendance: 70 old 1: insert into stud_rec values('&regno','&name','&major',&mark,&atttendance) new 1: insert into stud_rec values('002','john','cse',30,70) 1 row created. SQL> / Enter value for regno: 003 Enter value for name: arun Enter value for major: cse Enter value for mark: 90 Enter value for atttendance: 95 old 1: insert into stud_rec values('&regno','&name','&major',&mark,&atttendance) new 1: insert into stud_rec values('003','arun','cse',90,95) 1 row created. SQL> select * from stud_rec; REGNO NAME MARKS MAJOR ATTENDENCE 001 pinky cse 85 70 002 john cse 30 70 003 arun cse 90 95 create TRIGGER trig_attee_mark after update on stud_rec for each row begin if ( :new.attendence < 85 ) then dbms_output.put_line (:new.name || ' bearing REG.NO. '|| :new.regno || ' has attendence less than 85 ' ); end if; if ( :new.mark < 40 ) then dbms_output.put_line (:new.name || ' bearing REG.NO. '|| :new.regno || ' got mark less than 40 ' ); end if; end; Trigger created. SQL> select * from stud_rec; REGNO NAME MARKS MAJOR ATTENDENCE 001 pinky cse 85 70
  • 13. Advances in Database Management Systems Laboratory Work 2014-2015 13 002 john cse 30 70 003 arun cse 90 95 SQL> update stud_rec set attendence=25 where regno='001'; 1 row updated. SQL> select * from stud_rec; REGNO NAME MARKS MAJOR ATTENDENCE 001 pinky cse 85 25 002 john cse 30 70 003 arun cse 90 95
  • 14. Advances in Database Management Systems Laboratory Work 2014-2015 14 PROGRAM 4. Design, develop and execute a program in a language of your choice to implement any one algorithm for mining association rules. Run the program against any large database available in the public domain and discuss the results. Theory:- Apriori is a classic algorithm for frequent itemset mining and association rule learning over transactional databases. It proceeds by identifying the frequent individual items in the database and extending them to larger and larger item sets as long as those item sets appear sufficiently often in the database. The frequent item sets determined by Apriori can be used to determine association rules which highlight general trends in the database: this has applications in domains such as market basket analysis. Steps in execution: STEP 1: Create two notepad files and name them config.txt and transa.txt respectively. STEP 2: In config.txt file, insert 3 lines of input line 1 - number of items per transaction line 2 - number of transactions line 3 –minsup STEP 3: In transa.txt file, which is the transaction file, where the input is separated by space. STEP 4: These two input files belongs to the class AprioriCalculation.Copy these two input files in the specified path STEP 5: Run the program in netbeans.
  • 15. Advances in Database Management Systems Laboratory Work 2014-2015 15 package apriori; import java.io.*; import java.util.*; public class Apriori { public static void main(String[] args) { AprioriCalculationap = new AprioriCalculation(); ap.aprioriProcess(); } } /*************************************************************** * Class Name : AprioriCalculation * Purpose : generate Aprioriitemsets ***************************************************************/ class AprioriCalculation { Vector<String> candidates=new Vector<String>(); //the current candidates String configFile="config.txt"; //configuration file String transaFile="transa.txt"; //transaction file String outputFile="apriori-output.txt";//output file intnumItems; //number of items per transaction intnumTransactions; //number of transactions double minSup; //minimum support for a frequent itemset String oneVal[]; //array of value per column that will be treated as a '1' String itemSep = " "; //the separator value for items in the database
  • 16. Advances in Database Management Systems Laboratory Work 2014-2015 16 /*************************************************************** * Method Name : aprioriProcess * Purpose : Generate the aprioriitemsets * Parameters : None * Return : None ***************************************************************/ public void aprioriProcess() { Date d; //date object for timing purposes long start, end; //start and end time intitemsetNumber=0; //the current itemset being looked at //get config getConfig(); System.out.println("Apriori algorithm has started.n"); //start timer d = new Date(); start = d.getTime(); //while not complete do { //increase the itemset that is being looked at itemsetNumber++; //generate the candidates generateCandidates(itemsetNumber); //determine and display frequent itemsets calculateFrequentItemsets(itemsetNumber); if(candidates.size()!=0) { System.out.println("Frequent " + itemsetNumber + "-itemsets");
  • 17. Advances in Database Management Systems Laboratory Work 2014-2015 17 System.out.println(candidates); } //if there are <=1 frequent items, then its the end. This prevents reading through the database again. When there is only one frequent itemset. }while(candidates.size()>1); //end timer d = new Date(); end = d.getTime(); //display the execution time System.out.println("Execution time is: "+((double)(end-start)/1000) + " seconds."); } /*************************************************************** * Method Name : getInput * Purpose : get user input from System.in * Parameters : None * Return : String value of the users input ***************************************************************/ public static String getInput() { String input=""; //read from System.in BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); //try to get users input, if there is an error print the message try { input = reader.readLine(); } catch (Exception e) { System.out.println(e);
  • 18. Advances in Database Management Systems Laboratory Work 2014-2015 18 } return input; } /*************************************************************** * Method Name : getConfig * Purpose : get the configuration information (config filename, transaction filename) *: configFile and transaFile will be change appropriately * Parameters : None * Return : None ***************************************************************/ private void getConfig() { FileWriterfw; BufferedWriterfile_out; String input=""; //ask if want to change the config System.out.println("Default Configuration: "); System.out.println("tRegular transaction file with '" + itemSep + "' item separator."); System.out.println("tConfig File: " + configFile); System.out.println("tTransa File: " + transaFile); System.out.println("tOutput File: " + outputFile); System.out.println("nPress 'C' to change the item separator, configuration file and transaction files"); System.out.print("or any other key to continue. "); input=getInput(); if(input.compareToIgnoreCase("c")==0) { System.out.print("Enter new transaction filename (return for '"+transaFile+"'): "); input=getInput();
  • 19. Advances in Database Management Systems Laboratory Work 2014-2015 19 if(input.compareToIgnoreCase("")!=0) transaFile=input; System.out.print("Enter new configuration filename (return for '"+configFile+"'): "); input=getInput(); if(input.compareToIgnoreCase("")!=0) configFile=input; System.out.print("Enter new output filename (return for '"+outputFile+"'): "); input=getInput(); if(input.compareToIgnoreCase("")!=0) outputFile=input; System.out.println("Filenames changed"); System.out.print("Enter the separating character(s) for items (return for '"+itemSep+"'): "); input=getInput(); if(input.compareToIgnoreCase("")!=0) itemSep=input; } try { FileInputStreamfile_in = new FileInputStream(configFile); BufferedReaderdata_in = new BufferedReader(new InputStreamReader(file_in)); //number of items numItems=Integer.valueOf(data_in.readLine()).intValue(); //number of transactions numTransactions=Integer.valueOf(data_in.readLine()).intValue(); //minsup minSup=(Double.valueOf(data_in.readLine()).doubleValue());
  • 20. Advances in Database Management Systems Laboratory Work 2014-2015 20 //output config info to the user System.out.print("nInput configuration: "+numItems+" items, "+numTransactions+" transactions, "); System.out.println("minsup = "+minSup+"%"); System.out.println(); minSup/=100.0; oneVal = new String[numItems]; System.out.print("Enter 'y' to change the value each row recognizes as a '1':"); if(getInput().compareToIgnoreCase("y")==0) { for(inti=0; i<oneVal.length; i++) { System.out.print("Enter value for column #" + (i+1) + ": "); oneVal[i] = getInput(); } } else for(inti=0; i<oneVal.length; i++) oneVal[i]="1"; //create the output file fw= new FileWriter(outputFile); file_out = new BufferedWriter(fw); //put the number of transactions into the output file file_out.write(numTransactions + "n"); file_out.write(numItems + "n******n"); file_out.close(); } //if there is an error, print the message catch(IOException e) {
  • 21. Advances in Database Management Systems Laboratory Work 2014-2015 21 System.out.println(e); } } /*************************************************************** * Method Name : generateCandidates * Purpose : Generate all possible candidates for the n-thitemsets * : these candidates are stored in the candidates class vector * Parameters : n - integer value representing the current itemsets to be created * Return : None ***************************************************************/ private void generateCandidates(int n) { Vector<String>tempCandidates = new Vector<String>(); //temporary candidate string vector String str1, str2; //strings that will be used for comparisons StringTokenizer st1, st2; //string tokenizers for the two itemsets being compared //if its the first set, candidates are just the numbers if(n==1) { for(inti=1; i<=numItems; i++) { tempCandidates.add(Integer.toString(i)); } } else if(n==2) //second itemset is just all combinations of itemset 1 { //add each itemset from the previous frequent itemsets together for(inti=0; i<candidates.size(); i++) { st1 = new StringTokenizer(candidates.get(i)); str1 = st1.nextToken(); for(int j=i+1; j<candidates.size(); j++) {
  • 22. Advances in Database Management Systems Laboratory Work 2014-2015 22 st2 = new StringTokenizer(candidates.elementAt(j)); str2 = st2.nextToken(); tempCandidates.add(str1 + " " + str2); } } } else { //for each itemset for(inti=0; i<candidates.size(); i++) { //compare to the next itemset for(int j=i+1; j<candidates.size(); j++) { //create the strigns str1 = new String(); str2 = new String(); //create the tokenizers st1 = new StringTokenizer(candidates.get(i)); st2 = new StringTokenizer(candidates.get(j)); //make a string of the first n-2 tokens of the strings for(int s=0; s<n-2; s++) { str1 = str1 + " " + st1.nextToken(); str2 = str2 + " " + st2.nextToken(); } //if they have the same n-2 tokens, add them together if(str2.compareToIgnoreCase(str1)==0) tempCandidates.add((str1 + " " + st1.nextToken() + " " + st2.nextToken()).trim()); } }
  • 23. Advances in Database Management Systems Laboratory Work 2014-2015 23 } //clear the old candidates candidates.clear(); //set the new ones candidates = new Vector<String>(tempCandidates); tempCandidates.clear(); } /*************************************************************** * Method Name : calculateFrequentItemsets * Purpose : Determine which candidates are frequent in the n-thitemsets * from all possible candidates * Parameters : n - iteger representing the current itemsets being evaluated ***************************************************************/ private void calculateFrequentItemsets(int n) { Vector<String>frequentCandidates = new Vector<String>(); //the frequent candidates for the current itemset FileInputStreamfile_in; //file input stream BufferedReaderdata_in; //data input stream FileWriterfw; BufferedWriterfile_out; StringTokenizerst, stFile; //tokenizer for candidate and transaction boolean match; //whether the transaction has all the items in an itemset boolean trans[] = new boolean[numItems]; //array to hold a transaction so that can be checked int count[] = new int[candidates.size()]; //the number of successful matches try { //output file fw= new FileWriter(outputFile, true); file_out = new BufferedWriter(fw); //load the transaction file
  • 24. Advances in Database Management Systems Laboratory Work 2014-2015 24 file_in = new FileInputStream(transaFile); data_in = new BufferedReader(new InputStreamReader(file_in)); //for each transaction for(inti=0; i<numTransactions; i++) { //System.out.println("Got here " + i + " times"); //useful to debug files that you are unsure of the number of line stFile = new StringTokenizer(data_in.readLine(), itemSep); //read a line from the file to the tokenizer //put the contents of that line into the transaction array for(int j=0; j<numItems; j++) { trans[j]=(stFile.nextToken().compareToIgnoreCase(oneVal[j])==0); //if it is not a 0, assign the value to true } //check each candidate for(int c=0; c<candidates.size(); c++) { match = false; //reset match to false //tokenize the candidate so that we know what items need to be present for a match st = new StringTokenizer(candidates.get(c)); //check each item in the itemset to see if it is present in the transaction while(st.hasMoreTokens()) { match = (trans[Integer.valueOf(st.nextToken())-1]); if(!match) //if it is not present in the transaction stop checking break; } if(match) //if at this point it is a match, increase the count count[c]++; }
  • 25. Advances in Database Management Systems Laboratory Work 2014-2015 25 } for(inti=0; i<candidates.size(); i++) { // System.out.println("Candidate: " + candidates.get(c) + " with count: " + count + " % is: " + (count/(double)numItems)); //if the count% is larger than the minSup%, add to the candidate to the frequent candidates if((count[i]/(double)numTransactions)>=minSup) { frequentCandidates.add(candidates.get(i)); //put the frequent itemset into the output file file_out.write(candidates.get(i) + "," + count[i]/(double)numTransactions + "n"); } } file_out.write("-n"); file_out.close(); } //if error at all in this process, catch it and print the error messate catch(IOException e) { System.out.println(e); } //clear old candidates candidates.clear(); //new candidates are the old frequent candidates candidates = new Vector<String>(frequentCandidates); frequentCandidates.clear(); } }
  • 26. Advances in Database Management Systems Laboratory Work 2014-2015 26 Input:
  • 27. Advances in Database Management Systems Laboratory Work 2014-2015 27 Output:-