Anda di halaman 1dari 41

Advanced Database Management System Laboratory

1. Develop a database application to demonstrate storing and retrieving of BLOB and CLOB objects. /***blobclob.java***/
import java.sql.*; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.sql.DriverManager; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFileChooser; public class RegForm extends javax.swing.JFrame { /** Creates new form RegForm */ public RegForm() { initComponents(); this.addRadio.setSelected(true); this.viewGroup.add(this.addRadio); this.viewGroup.add(this.retriveRadio); } public String photoFilePath; public String addressFilePath; public String id; public String sname; public String srno; public String saddress; public String sphoto; String driverName = "sun.jdbc.odbc.JdbcOdbcDriver"; String url = "jdbc:odbc:stud12"; //String dbName = "hibernatetutorial"; String userName = "system"; String password = "Vinuta123"; @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() {

Dept. Computer Science & Engg.

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory viewGroup = new javax.swing.ButtonGroup(); jButton2 = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); rnoJtxt = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); nameJtxt = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); addressJtxt = new javax.swing.JTextField(); addressJbtn = new javax.swing.JButton(); jLabel4 = new javax.swing.JLabel(); photoJtxt = new javax.swing.JTextField(); photoJbtn = new javax.swing.JButton(); addRecJbtn = new javax.swing.JButton(); jPanel2 = new javax.swing.JPanel(); jLabel5 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); addRadio = new javax.swing.JRadioButton(); retriveRadio = new javax.swing.JRadioButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jButton2.setText("Exit"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("DATA ENTRY")); jLabel1.setText("Roll No:"); jLabel2.setText("Name:"); jLabel3.setText("Address:"); addressJtxt.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addressJtxtActionPerformed(evt); } }); addressJbtn.setText("Select Address"); addressJbtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addressJbtnActionPerformed(evt); } }); jLabel4.setText("Photo:"); photoJbtn.setText("Select Photo"); photoJbtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) {

Dept. Computer Science & Engg.

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory photoJbtnActionPerformed(evt); } }); addRecJbtn.setText("Add"); addRecJbtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addRecJbtnActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING ) .addComponent(jLabel2) .addComponent(jLabel1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(rnoJtxt, javax.swing.GroupLayout.DEFAULT_SIZE, 154, Short.MAX_VALUE) .addComponent(nameJtxt, javax.swing.GroupLayout.DEFAULT_SIZE, 154, Short.MAX_VALUE))) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, 43, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(photoJtxt, javax.swing.GroupLayout.DEFAULT_SIZE, 154, Short.MAX_VALUE) .addComponent(addressJtxt, javax.swing.GroupLayout.DEFAULT_SIZE, 154, Short.MAX_VALUE)))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(photoJbtn, javax.swing.GroupLayout.DEFAULT_SIZE, 103, Short.MAX_VALUE) .addComponent(addressJbtn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))

Dept. Computer Science & Engg.

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory .addGroup(jPanel1Layout.createSequentialGroup() .addGap(105, 105, 105) .addComponent(addRecJbtn))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(21, 21, 21) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELIN E) .addComponent(jLabel1) .addComponent(rnoJtxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELIN E) .addComponent(jLabel2) .addComponent(nameJtxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELIN E) .addComponent(addressJtxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3) .addComponent(addressJbtn)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELIN E) .addComponent(photoJtxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(photoJbtn) .addComponent(jLabel4)) .addGap(32, 32, 32) .addComponent(addRecJbtn) .addContainerGap(83, Short.MAX_VALUE)) ); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("DATA RETRIEVAL")); jLabel5.setText("Rno"); jTextField1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField1ActionPerformed(evt);

Dept. Computer Science & Engg.

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory } }); jButton1.setText("Retrieve"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel5) .addGap(28, 28, 28) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(90, 90, 90) .addComponent(jButton1))) .addContainerGap(192, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(36, 36, 36) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELIN E) .addComponent(jLabel5) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(30, 30, 30) .addComponent(jButton1) .addContainerGap(190, Short.MAX_VALUE)) ); addRadio.setText("Add Record"); addRadio.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { addRadioStateChanged(evt); }

Dept. Computer Science & Engg.

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory }); retriveRadio.setText("Retrive Record"); retriveRadio.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { retriveRadioStateChanged(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(29, 29, 29) .addComponent(addRadio) .addGap(18, 18, 18) .addComponent(retriveRadio) .addGap(100, 100, 100) .addComponent(jButton2))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 36, Short.MAX_VALUE) .addComponent(jButton2) .addGap(152, 152, 152))

Dept. Computer Science & Engg.

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory .addGroup(layout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(addRadio) .addComponent(retriveRadio)) .addContainerGap()))) ); pack(); }// </editor-fold>//GEN-END:initComponents private void addressJtxtActionPerformed(java.awt.event.ActionEvent evt) {//GENFIRST:event_addressJtxtActionPerformed // TODO add your handling code here: }//GEN-LAST:event_addressJtxtActionPerformed public static void p(String msg) { System.out.println(msg); } private void photoJbtnActionPerformed(java.awt.event.ActionEvent evt) {//GENFIRST:event_photoJbtnActionPerformed // TODO add your handling code here:g this.photoJtxt.setText(RegForm.selectFile(this)); this.photoFilePath=this.photoJtxt.getText(); } private void addressJbtnActionPerformed(java.awt.event.ActionEvent evt) { this.addressJtxt.setText(RegForm.selectFile(this)); this.addressFilePath=this.addressJtxt.getText(); RegForm.p("Text path==="+this.addressFilePath); byte data[]=RegForm.readFileInBytes(this.addressFilePath); this.saddress=RegForm.byteToStringAddress(data); } private void addRecJbtnActionPerformed(java.awt.event.ActionEvent evt) {//GENFIRST:event_addRecJbtnActionPerformed try { // TODO add your handling code here: this.srno=this.rnoJtxt.getText(); if(srno.isEmpty() ) { javax.swing.JOptionPane.showMessageDialog( RegForm.this, "Empty Rollno Field" ); } this.sname=this.nameJtxt.getText(); if(sname.isEmpty() ) { javax.swing.JOptionPane.showMessageDialog( RegForm.this, "Empty Name Field" ); } if(addressFilePath.isEmpty() ) {

Dept. Computer Science & Engg.

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory javax.swing.JOptionPane.showMessageDialog( RegForm.this, "Empty Adress Field" ); } if(photoFilePath.isEmpty() ) { javax.swing.JOptionPane.showMessageDialog( RegForm.this, "Empty Photo Field" ); } Class.forName(driverName); Connection conn = DriverManager.getConnection(url, userName, password); String INSERT_STUDENT = "insert into student(rno, name, addrs, photo) values (?, ?, ?, ?)"; FileInputStream fis = null; PreparedStatement ps = null; conn.setAutoCommit(false); ps = (PreparedStatement) conn.prepareStatement(INSERT_STUDENT); ps.setString(1,this.srno); ps.setString(2,this.sname); //ps.setString(3,this.saddress); File data = new File(this.addressFilePath); FileReader reader = new FileReader(data); ps.setCharacterStream(3, reader, (int) data.length()); File file = new File(this.photoFilePath); fis = new FileInputStream(file); ps.setBinaryStream(4, (InputStream)fis, (int) file.length()); //ps.executeQuery(); ps.executeUpdate(); // ps.executeUpdate(); conn.commit(); System.out.println("Insertion Successful"); } catch(Exception e) { System.out.println(e); } }//GEN-LAST:event_addRecJbtnActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GENFIRST:event_jButton1ActionPerformed try { Class.forName(driverName); Connection conn = DriverManager.getConnection(url, userName, password); PreparedStatement stmt = null; try { this.id=this.jTextField1.getText(); if(id.isEmpty() ) { javax.swing.JOptionPane.showMessageDialog( RegForm.this, "Empty Rollno Field" ); } String query = "select * from student where rno="+id;

Dept. Computer Science & Engg.

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory System.out.println(query); stmt =(PreparedStatement) conn.prepareStatement(query); ResultSet rs = (ResultSet) stmt.executeQuery(); if(rs.next()){ String Name = rs.getString(2); System.out.println(id + "\t" + Name); File data = new File("E:\\abc.txt"); Reader reader = rs.getCharacterStream(3); FileWriter writer = new FileWriter(data); char[] buffer = new char[1]; while (reader.read(buffer) > 0) { writer.write(buffer); System.out.print(buffer); } writer.close(); File image1 = new File("E:\\java.gif"); FileOutputStream fos = new FileOutputStream(image1); byte[] buffer1 = new byte[1]; InputStream is = rs.getBinaryStream(4); while (is.read(buffer1) > 0) { fos.write(buffer1); //System.out.print(buffer1); } fos.close(); javax.swing.JOptionPane.showMessageDialog( RegForm.this, " Found"); } else javax.swing.JOptionPane.showMessageDialog( RegForm.this, "Not Found"); System.out.println("Successful"); conn.close(); } catch (IOException ex) { Logger.getLogger(RegForm.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException e ) { //JDBCTutorialUtilities.printSQLException(e); } finally { if (stmt != null) { stmt.close(); } } // TODO add your handling code here: } catch (ClassNotFoundException ex) { Logger.getLogger(RegForm.class.getName()).log(Level.SEVERE, null, ex); } catch (SQLException ex ) { Logger.getLogger(RegForm.class.getName()).log(Level.SEVERE, null, ex); //JDBCTutorialUtilities.printSQLException(e); } }//GEN-LAST:event_jButton1ActionPerformed

Dept. Computer Science & Engg.

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GENFIRST:event_jButton2ActionPerformed System.exit(0);// TODO add your handling code here: }//GEN-LAST:event_jButton2ActionPerformed private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GENFIRST:event_jTextField1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField1ActionPerformed private void addRadioStateChanged(javax.swing.event.ChangeEvent evt) {//GENFIRST:event_addRadioStateChanged // TODO add your handling code here: if(this.addRadio.isSelected()) { this.jPanel1.setVisible(true); this.jPanel2.setVisible(false); } }//GEN-LAST:event_addRadioStateChanged private void retriveRadioStateChanged(javax.swing.event.ChangeEvent evt) {//GENFIRST:event_retriveRadioStateChanged // TODO add your handling code here: if(this.retriveRadio.isSelected()) { this.jPanel1.setVisible(false); this.jPanel2.setVisible(true); } }//GEN-LAST:event_retriveRadioStateChanged public static void main(String args[]) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(RegForm.class.getName()).log(java.util.logging.Level.SEVE RE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(RegForm.class.getName()).log(java.util.logging.Level.SEVE RE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(RegForm.class.getName()).log(java.util.logging.Level.SEVE RE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) {

Dept. Computer Science & Engg.

10

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory java.util.logging.Logger.getLogger(RegForm.class.getName()).log(java.util.logging.Level.SEVE RE, null, ex); } /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new RegForm().setVisible(true); } }); } public static byte[] readFileInBytes(String filePath) { FileInputStream fis = null; byte[] fileBArray = null; BufferedInputStream bin = null; File file = new File(filePath); try { fis = new FileInputStream(file); bin = new BufferedInputStream(fis); fileBArray = new byte[(int) file.length()]; bin.read(fileBArray); // String t=""; return fileBArray; } catch (FileNotFoundException e) { System.out.println("File not found" + e); return fileBArray; } catch (IOException ioe) { System.out.println("Exception while reading the file " + ioe); } finally { //close the BufferedInputStream using close method try { if (bin != null) { bin.close(); } } catch (IOException ioe) { System.out.println("Error while closing the stream : " + ioe); } } return fileBArray; } public static String byteToStringPhoto(byte[] data) { String temp=""; for (int i=0;i<data.length ; i++) { temp = temp +data[i]; } return temp;

Dept. Computer Science & Engg.

11

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory } public static String byteToStringAddress(byte[] data) { char t1[]=new char[data.length]; int i=0; for(byte b:data) { t1[i++]=(char)b; } String textData=new String(t1); System.out.print(t1); return textData; } public static String selectFile(javax.swing.JFrame parent) { String path = ""; javax.swing.JFileChooser jFileChooser1 = new javax.swing.JFileChooser(); jFileChooser1.setFileSelectionMode(JFileChooser.FILES_ONLY); int returnVal = jFileChooser1.showOpenDialog(parent); if (returnVal == JFileChooser.APPROVE_OPTION) { File f = jFileChooser1.getSelectedFile(); f.getAbsolutePath(); String dir = f.getAbsolutePath().toString(); path = RegForm.convt(dir); } return path; } public static String convt(String dir) { char d[] = dir.toCharArray(); String path = null; for (int cnt = 0; cnt < d.length; cnt++) { if (d[cnt] == 92) { d[cnt] = 47; } } path = String.copyValueOf(d); return path; } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JRadioButton addRadio; private javax.swing.JButton addRecJbtn; private javax.swing.JButton addressJbtn; private javax.swing.JTextField addressJtxt; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2;

Dept. Computer Science & Engg.

12

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JTextField jTextField1; private javax.swing.JTextField nameJtxt; private javax.swing.JButton photoJbtn; private javax.swing.JTextField photoJtxt; private javax.swing.JRadioButton retriveRadio; private javax.swing.JTextField rnoJtxt; private javax.swing.ButtonGroup viewGroup; // End of variables declaration//GEN-END:variables }

Dept. Computer Science & Engg.

13

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory OUTPUT:

Fig: Data Entry

Fig: Data Retrival

Dept. Computer Science & Engg.

14

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory

2. Develop a database application to demonstrate the representation of multivalued attributes, and the use of nested tables to represent complex objects. Write suitable queries to demonstrate their use.
Create a table with NESTED TABLE column: CREATE OR REPLACE TYPE my_tab_t AS TABLE OF VARCHAR2(30); CREATE TABLE nested_table (id NUMBER, col1 my_tab_t) NESTED TABLE col1 STORE AS col1_tab; Insert data into table: INSERT INTO nested_table VALUES (1, my_tab_t('A')); INSERT INTO nested_table VALUES (2, my_tab_t('B', 'C')); INSERT INTO nested_table VALUES (3, my_tab_t('D', 'E', 'F')); COMMIT; Select from nested table: SQL> SELECT * FROM nested_table; ID ---------1 2 3 COL1 -----------------------MY_TAB_T('A') MY_TAB_T('B', 'C') MY_TAB_T('D', 'E', 'F')

Unnesting the subtable: SQL> SELECT id, COLUMN_VALUE FROM nested_table t1, TABLE(t1.col1) t2; ID COLUMN_VALUE ---------- -----------------------1A 2B 2C 3D 3E 5 rows selected

Dept. Computer Science & Engg.

15

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory

TRIGGERS
A trigger is a PL/SQL block structure which is fired when a DML statement like Insert, Delete, and Update is executed on a database table. A trigger is triggered automatically when an associated DML statement is executed. Syntax of Triggers The Syntax for creating a trigger is: CREATE [OR REPLACE ] TRIGGER trigger_name {BEFORE | AFTER | INSTEAD OF } {INSERT [OR] | UPDATE [OR] | DELETE} [OF col_name] ON table_name [REFERENCING OLD AS o NEW AS n] [FOR EACH ROW] WHEN (condition) BEGIN --- sql statements END;

1. Level triggers. The trigger is fired only for rows that satisfy the condition specified. CREATE [OR REPLACE] TRIGGER trigger_name - This clause creates a trigger with the given name or overwrites an existing trigger with the same name. 2. {BEFORE | AFTER | INSTEAD OF } - This clause indicates at what time should the trigger get fired. i.e for example: before or after updating a table. INSTEAD OF is used to create a trigger on a view. before and after cannot be used to create a trigger on a view. 3. {INSERT [OR] | UPDATE [OR] | DELETE} - This clause determines the triggering event. More than one triggering events can be used together separated by OR keyword. The trigger gets fired at all the specified triggering event. 4. [OF col_name] - This clause is used with update triggers. This clause is used when you want to trigger an event only when a specific column is updated.

Dept. Computer Science & Engg.

16

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory 5. CREATE [OR REPLACE] TRIGGER trigger_name - This clause creates a trigger with the given name or overwrites an existing trigger with the same name. 6. [ON table_name] - This clause identifies the name of the table or view to which the trigger is associated. 7. [REFERENCING OLD AS o NEW AS n] - This clause is used to reference the old and new values of the data being changed. By default, you reference the values as :old.column_name or :new.column_name. The reference names can also be changed from old (or new) to any other user-defined name. You cannot reference old values when inserting a record, or new values when deleting a record, because they do not exist. 8. [FOR EACH ROW] - This clause is used to determine whether a trigger must fire when each row gets affected (i.e., a Row Level Trigger) or just once when the entire sql statement is executed(i.e. statement level Trigger). 9. WHEN (condition) - This clause is valid only for row Types of PL/SQL Triggers There are two types of triggers based on the which level it is triggered. 1) Row level trigger - An event is triggered for each row upated, inserted or deleted. 2) Statement level trigger - An event is triggered for each sql statement executed.

PL/SQL Trigger Execution Hierarchy The following hierarchy is followed when a trigger is fired. 1) BEFORE statement trigger fires first. 2) Next BEFORE row level trigger fires, once for each row affected. 3) Then AFTER row level trigger fires once for each affected row. This events will alternates between BEFORE and AFTER row level triggers. 4) Finally the AFTER statement level trigger fires.

Dept. Computer Science & Engg.

17

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory

3. Design and develop a suitable Student Database application. One of the attributes to me 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 are less than 40%; if so, notify the Head of the Department concerned.
DROP TABLE STUDENT_HOD; DROP TABLE ATTENDANCE; DROP TABLE NOTIFY; DROP TABLE INTERNAL_ASSESSMENT; DROP TABLE SUBJECT; DROP TABLE STUDENT; DROP TABLE HEAD_OF_DEPARTMENT;

CREATE TABLE STUDENT( STUDENT_ID VARCHAR2(20) PRIMARY KEY, STUDENT_NAME VARCHAR2(50) NOT NULL, STUDENT_EMAIL_ID VARCHAR2(50));

CREATE TABLE HEAD_OF_DEPARTMENT( HOD_ID VARCHAR2(20) PRIMARY KEY, HOD_NAME VARCHAR2(50) NOT NULL, HOD_EMAIL_ID VARCHAR2(50));

Dept. Computer Science & Engg.

18

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory CREATE TABLE SUBJECT( SUB_CODE VARCHAR2(20) PRIMARY KEY, SUB_NAME VARCHAR2(30) NOT NULL, SUB_MARKS NUMBER(10) DEFAULT 50);

CREATE TABLE STUDENT_HOD( STUDENT_ID VARCHAR2(20) NOT NULL REFERENCES STUDENT(STUDENT_ID), HOD_ID VARCHAR2(20) NOT NULL REFERENCES HEAD_OF_DEPARTMENT(HOD_ID), CONSTRAINT STUDENT_HOD_PK PRIMARY KEY(STUDENT_ID, HOD_ID));

CREATE TABLE INTERNAL_ASSESSMENT( STUDENT_ID VARCHAR2(20) NOT NULL REFERENCES STUDENT(STUDENT_ID), SUB_CODE VARCHAR2(20) NOT NULL REFERENCES SUBJECT(SUB_CODE), TEST_DATE DATE DEFAULT SYSDATE, MARKS_OBTAINED NUMBER(3) DEFAULT 0, CONSTRAINT INTERNAL_ASSESSMENT_pk PRIMARY KEY(STUDENT_ID, SUB_CODE, TEST_DATE));

CREATE TABLE ATTENDANCE( STUDENT_ID VARCHAR2(20) NOT NULL REFERENCES STUDENT(STUDENT_ID), SUB_CODE VARCHAR2(20) NOT NULL REFERENCES SUBJECT(SUB_CODE), ATTENDANCE_DATE DATE, STATUS VARCHAR2(1) CHECK STATUS IN('P','A'));

CREATE TABLE NOTIFY( HOD_ID VARCHAR2(20) NOT NULL REFERENCES HEAD_OF_DEPARTMENT(HOD_ID), REASON VARCHAR2(255) NOT NULL);

Dept. Computer Science & Engg.

19

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory CREATE TABLE ATTENDANCE( STUDENT_ID VARCHAR2(20) NOT NULL REFERENCES STUDENT(STUDENT_ID), SUB_CODE VARCHAR2(20) NOT NULL REFERENCES SUBJECT(SUB_CODE), ATTENDANCE_DATE DATE DEFAULT SYSDATE, STATUS CHAR(1) CONSTRAINT STATUS_CK CHECK (STATUS IN('P','A')));

DESC STUDENT DESC HEAD_OF_DEPARTMENT DESC SUBJECT DESC STUDENT_HOD DESC INTERNAL_ASSESSMENT DESC ATTENDANCE DESC NOTIFY

--- Trigger to check the internal_assessment marks.

CREATE OR REPLACE TRIGGER INTERNAL_ASSESSMENT_NOTIFY AFTER INSERT OR UPDATE ON INTERNAL_ASSESSMENT FOR EACH ROW DECLARE V_SUB_MARKS V_HOD_ID SUBJECT.SUB_MARKS%TYPE := NULL;

HEAD_OF_DEPARTMENT.HOD_ID%TYPE := NULL;

V_STUDENT_NAME STUDENT.STUDENT_NAME%TYPE := NULL; V_SUB_NAME BEGIN SELECT SUB_MARKS, SUB_NAME INTO V_SUB_MARKS, V_SUB_NAME FROM SUBJECT WHERE SUB_CODE = :NEW.SUB_CODE; SUBJECT.SUB_NAME%TYPE := NULL;

SELECT STUDENT_NAME INTO V_STUDENT_NAME FROM STUDENT WHERE STUDENT_ID = :NEW.STUDENT_ID;

SELECT HOD_ID INTO V_HOD_ID FROM STUDENT_HOD WHERE STUDENT_ID =

Dept. Computer Science & Engg.

20

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory :NEW.STUDENT_ID;

IF (V_SUB_MARKS IS NOT NULL AND V_SUB_NAME IS NOT NULL AND V_STUDENT_NAME IS NOT NULL AND V_HOD_ID IS NOT NULL) THEN IF (:NEW.MARKS_OBTAINED < (V_SUB_MARKS * 0.4)) THEN INSERT INTO NOTIFY VALUES(V_HOD_ID, V_STUDENT_NAME || ' (ID:- ' || :NEW.STUDENT_ID ||') HAS LESS THAN 40% MARKS IN SUBJECT ' || V_SUB_NAME); END IF; END IF; EXCEPTION WHEN OTHERS THEN NULL; END;

SELECT * FROM STUDENT; STUDENT_ID 1 2 3 4 STUDENT_NAME Sachin Kumar Mary Sam STUDENT_EMAIL_ID -

SELECT * FROM HEAD_OF_DEPARTMENT; HOD_ID 100 200 300 400 HOD_NAME Tim Venkatesh Gopal Anu HOD_EMAIL_ID tim@gmail.com Venkatesh@gmail.com Gopal@gmail.com Anu@gmail.com

Dept. Computer Science & Engg.

21

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory SELECT * FROM SUBJECT; SUB_CODE 01 02 03 SUB_NAME C++ JAVA DOT NET SUB_MARKS 50 50 5

SELECT * FROM STUDENT_HOD; STUDENT_ID 1 HOD_ID 100

SELECT * FROM INTERNAL_ASSESSMENT; STUDENT_ID 3 3 1 1 1 1 1 SUB_CODE 01 03 03 03 02 02 02 TEST_DATE 09-NOV-10 09-NOV-10 09-NOV-10 09-NOV-10 09-NOV-10 09-NOV-10 09-NOV-10 MARKS_OBTAINED 10 35 15 35 30 20 0

SELECT * FROM NOTIFY; HOD_ID 100 REASON Sachin (ID:- 1) HAS LESS THAN 40% MARKS IN SUBJECT JAVA

Dept. Computer Science & Engg.

22

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory

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.
MINING ASSOCIATION RULES Overview In this experiment we are implementing the Apriori algorithm to mining association rules from data file. The format of this documentation is organized as following. First, I introduce the basic concepts of association rules; then there is a description of the Apriori algorithm; also I will discuss the implementation of my program, introduce some test cases to show the work of Apriori. Finally I will discuss the generated result of a public domain datasets and end up with a conclusion. Association Rules Association rule mining finds interesting association or correlation relationships among a large set of data. Let's look at its basic concepts. Let J= {i1, i2, . Im} be a set of items. Let D be a set of database transactions where transaction T is a set of items suck that T belongs to J. Each transaction is associated with an identifier, let's call it TID. Let A be a set of items, a transaction T is said to contain A if and only if A belongs to T. An association rule is an implication of the form A=>B, where A is a proper subset of J, B is a proper subset of J, and the intersection of A and B is an empty set. The rule A=>B holds in the transaction set D with supports s, where s is the percentage of transaction in D that contain both A and B. The rule A=>B has confidence c in the transaction set D if c is the percentage of transactions in D containing A that also contain B. Usually a set of items is referred to as an item set. The occurrence frequency of an item set is the number of transactions that contain the item set. This is also known as support count or frequency.Let's have an example. Super store sales a lot of items everyday, but the sales manager want to know the internal relationship of those items, which has been sold.

Dept. Computer Science & Engg.

23

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory

TID

ITEM ID

T1

I1,I2,I3

T2

I2,I3

T3

I2,I4

Table : An example of Transaction lists

From above table, transaction ID is denoted as T1, T2, T3; D is the database of transactions including T1, T2, and T3. I1, I2, I3, I4 are items; each transaction is a set of items, for example T1 includes I1, I2, I3. Now we have an idea about association rules, let's move on to the Apriori algorithm.

The Apriori Algorithm Apriori is an influentiall algorithm for mining frequent item sets for Boolean

Dept. Computer Science & Engg.

24

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory association rules. Apriori has an important property: all nonempty subsets of a frequent

item set must also be frequent. So, how is this property used in the algorithm? In order to show this, two-step process is introduced including a join step and a prune step. Please take a look at how Lk-1 is used to find Lk. In steps 2-10, Lk is used to generate candidated Ck in order to find Lk. The apriori_gen procedure generates the candidates and then uses the Apriori property to eliminate those having a subset that is not frequent (step 3). The apriori_gen procedure contains following as shown in figure 2 and figure 3.

Figure 2 The join step

Figure 3 The prune step

Dept. Computer Science & Engg.

25

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory The Implementation of Apriori In this section, I will introduce how my program implements above procedures. All the procedures are included in a Java source file called apriori.java. Input File Format It is important that have a correct source file in order to generate the correct result. If the source file invalid, then program might be crushed or cannot produce the correct result. In this section, I will discuss the file format that the program recognizes.

Fig 4: Input File Format Figure 4 shows a input file , the four lines are transactions ( this sample has 04 transactions, but your input file can have as many as you want), each line is a transaction, and each transaction contains one or more items. For instance, {1,2,3} is a transaction, and 1, 2, 3 are items, which are separated by a space.

Fig 5: Configuration file

Figure 5 shows a configure file which contains configuration details for program,i.e., There are 5- elements in the input file, consisting of 4 transactions & the minimum support

Dept. Computer Science & Engg.

26

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory required is 50%. We can modify this configuration by changing the values in the input file based on user requirement.

/***apriori.java***/ import java.io.*; import java.util.*; //------------------------------------------------------------// Class Name : apriori // Purpose : main program class //------------------------------------------------------------public class Apriori { public static void main(String[] args) throws IOException { aprioriProcess process1=new aprioriProcess(); System.exit(0); } } //------------------------------------------------------------// Class Name : aprioriProcess // Purpose : main processing class //------------------------------------------------------------class aprioriProcess { private final int HT=1; // state of tree node (hash table or private final int IL=2; // itemset list) int N; // total item # int M; // total transaction # Vector largeitemset=new Vector(); Vector candidate=new Vector(); int minsup; String fullitemset; String configfile="config.txt"; String transafile="transa.txt"; //------------------------------------------------------------// Class Name : candidateelement // Purpose : object that will be stored in Vector candidate // : include 2 item // : a hash tree and a candidate list //------------------------------------------------------------class candidateelement { hashtreenode htroot; Vector candlist;

Dept. Computer Science & Engg.

27

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory } //------------------------------------------------------------// Class Name : hashtreenode // Purpose : node of hash tree //------------------------------------------------------------class hashtreenode { int nodeattr; // IL or HT int depth; Hashtable ht; Vector itemsetlist; public void hashtreenode() { nodeattr=HT; ht=new Hashtable(); itemsetlist=new Vector(); depth=0; } public void hashtreenode(int i) { nodeattr=i; ht=new Hashtable(); itemsetlist=new Vector(); depth=0; } } //------------------------------------------------------------// Class Name : itemsetnode // Purpose : node of itemset //------------------------------------------------------------class itemsetnode { String itemset; int counter; public itemsetnode(String s1,int i1) { itemset=new String(s1); counter=i1; } public itemsetnode() { itemset=new String(); counter=0; } public String toString() { String tmp=new String(); tmp=tmp.concat("<\"");

Dept. Computer Science & Engg.

28

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory tmp=tmp.concat(itemset); tmp=tmp.concat("\","); tmp=tmp.concat(Integer.toString(counter)); tmp=tmp.concat(">"); return tmp; } } //------------------------------------------------------------// Method Name: printhashtree // Purpose : print the whole hash tree // Parameter : htn is a hashtreenode (when other method call this method,it is the root) // : transa : special transaction with all items occurr in it. // : a : recursive depth // Return : //------------------------------------------------------------public void printhashtree(hashtreenode htn,String transa,int a) { if (htn.nodeattr == IL ) { System.out.println("Node is an itemset list"); System.out.println(" depth :<"+htn.depth+">"); System.out.println(" iteset:<"+htn.itemsetlist+">"); } else { // HT System.out.println("Node is a hashtable"); if (htn.ht==null) return; for (int b=a+1;b<=N;b++) if (htn.ht.containsKey(Integer.toString(getitemat(b,transa)))) { System.out.println(" key:<"+getitemat(b,transa)); printhashtree((hashtreenode)htn.ht.get(Integer.toString(getitemat(b,transa))),transa,b); } } } //------------------------------------------------------------// Method Name: getconfig // Purpose : open file config.txt // : get the total number of items of transaction file // : and the total number of transactions // : and minsup //------------------------------------------------------------public void getconfig() throws IOException { FileInputStream file_in; DataInputStream data_in; String oneline=new String(); int i=0;

Dept. Computer Science & Engg.

29

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory InputStreamReader input = new InputStreamReader(System.in); BufferedReader reader = new BufferedReader(input); String response = ""; System.out.println("Press 'C' to change the default configuration and transaction files"); System.out.print("or any other key to continue. "); try { response = reader.readLine(); } catch (Exception e) { System.out.println(e); } int res=response.compareTo("C") * response.compareTo("c"); if(res == 0) { System.out.print("\nEnter new transaction filename: "); try { transafile = reader.readLine(); } catch (Exception e) { System.out.println(e); } System.out.print("Enter new configuration filename: "); try { configfile = reader.readLine(); } catch (Exception e) { System.out.println(e); } System.out.println("Filenames changed"); } try { file_in = new FileInputStream(configfile); data_in = new DataInputStream(file_in); oneline=data_in.readLine(); N=Integer.valueOf(oneline).intValue(); oneline=data_in.readLine(); M=Integer.valueOf(oneline).intValue(); oneline=data_in.readLine(); minsup=Integer.valueOf(oneline).intValue(); System.out.print("\nInput configuration: "+N+" items, "+M+" transactions, "); System.out.println("minsup = "+minsup+"%"); System.out.println(); } catch (IOException e) { System.out.println(e); }

Dept. Computer Science & Engg.

30

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory } //------------------------------------------------------------// Method Name: getitemat // Purpose : get an item from an itemset // : get the total number of items of transaction file // Parameter : int i : i-th item ; itemset : string itemset // Return : int : the item at i-th in the itemset //------------------------------------------------------------public int getitemat(int i,String itemset) { String str1=new String(itemset); StringTokenizer st=new StringTokenizer(itemset); int j; if (i > st.countTokens()) System.out.println("eRRor! in getitemat, !!!!"); for (j=1;j<=i;j++) str1=st.nextToken(); return(Integer.valueOf(str1).intValue()); } //------------------------------------------------------------// Method Name: itesetsize // Purpose : get item number of an itemset // Parameter : itemset : string itemset // Return : int : the number of item of the itemset //------------------------------------------------------------public int itemsetsize(String itemset) { StringTokenizer st=new StringTokenizer(itemset); return st.countTokens(); } //------------------------------------------------------------// Method Name: gensubset // Purpose : generate all subset given an itemset // Parameter : itemset // Return : a string contains all subset deliminated by "," // : e.g. "1 2,1 3,2 3" is subset of "1 2 3" //------------------------------------------------------------public String gensubset(String itemset) { int len=itemsetsize(itemset); int i,j; String str1; String str2=new String(); String str3=new String(); if (len==1) return null;

Dept. Computer Science & Engg.

31

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory for (i=1;i<=len;i++) { StringTokenizer st=new StringTokenizer(itemset); str1=new String(); for (j=1;j<i;j++) { str1=str1.concat(st.nextToken()); str1=str1.concat(" "); } str2=st.nextToken(); for (j=i+1;j<=len;j++) { str1=str1.concat(st.nextToken()); str1=str1.concat(" "); } if (i!=1) str3=str3.concat(","); str3=str3.concat(str1.trim()); } return str3; } //end public String gensubset(String itemset) //------------------------------------------------------------// Method Name: createcandidate // Purpose : generate candidate n-itemset // Parameter : int n : n-itemset // Return : Vector : candidate is stored in a Vector //------------------------------------------------------------public Vector createcandidate(int n) { Vector tempcandlist=new Vector(); Vector ln_1=new Vector(); int i,j,length1; String cand1=new String(); String cand2=new String(); String newcand=new String(); //System.out.println("Generating "+n+"-candidate item set ...."); if (n==1) for (i=1;i<=N;i++) tempcandlist.addElement(Integer.toString(i)); else { ln_1=(Vector)largeitemset.elementAt(n-2); length1=ln_1.size(); for (i=0;i<length1;i++) { cand1=(String)ln_1.elementAt(i); for (j=i+1;j<length1;j++) { cand2=(String)ln_1.elementAt(j); newcand=new String(); if (n==2) { newcand=cand1.concat(" ");

Dept. Computer Science & Engg.

32

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory newcand=newcand.concat(cand2); tempcandlist.addElement(newcand.trim()); } else { int c,i1,i2; boolean same=true; for (c=1;c<=n-2;c++) { i1=getitemat(c,cand1); i2=getitemat(c,cand2); if ( i1!=i2 ) { same=false; break; } else { newcand=newcand.concat(" "); newcand=newcand.concat(Integer.toString(i1)); } } if (same) { i1=getitemat(n-1,cand1); i2=getitemat(n-1,cand2); newcand=newcand.concat(" "); newcand=newcand.concat(Integer.toString(i1)); newcand=newcand.concat(" "); newcand=newcand.concat(Integer.toString(i2)); tempcandlist.addElement(newcand.trim()); } } //end if n==2 else } //end for j } //end for i } //end if n==1 else if (n<=2) return tempcandlist; Vector newcandlist=new Vector(); for (int c=0; c<tempcandlist.size(); c++) { String c1=(String)tempcandlist.elementAt(c); String subset=gensubset(c1); StringTokenizer stsubset=new StringTokenizer(subset,","); boolean fake=false; while (stsubset.hasMoreTokens()) if (!ln_1.contains(stsubset.nextToken())) { fake=true; break;

Dept. Computer Science & Engg.

33

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory } if (!fake) newcandlist.addElement(c1); } return newcandlist; } //end public createcandidate(int n) //------------------------------------------------------------// Method Name: createcandidatehashtre // Purpose : generate candidate hash tree // Parameter : int n : n-itemset // Return : hashtreenode : root of the hashtree //------------------------------------------------------------public hashtreenode createcandidatehashtree(int n) { int i,len1; hashtreenode htn=new hashtreenode(); //System.out.println("Generating candidate "+n+"-itemset hashtree ...."); if (n==1) htn.nodeattr=IL; else htn.nodeattr=HT; len1=((candidateelement)candidate.elementAt(n-1)).candlist.size(); for (i=1;i<=len1;i++) { String cand1=new String(); cand1=(String)((candidateelement)candidate.elementAt(n-1)).candlist.elementAt(i-1); genhash(1,htn,cand1); } return htn; } //end public createcandidatehashtree(int n) //------------------------------------------------------------// Method Name: genhash // Purpose : called by createcandidatehashtree // : recursively generate hash tree node // Parameter : htnf is a hashtreenode (when other method call this method,it is the root) // : cand : candidate itemset string // : int i : recursive depth,from i-th item, recursive // Return : //------------------------------------------------------------public void genhash(int i, hashtreenode htnf, String cand) { int n=itemsetsize(cand);

Dept. Computer Science & Engg.

34

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory if (i==n) { htnf.nodeattr=IL; htnf.depth=n; itemsetnode isn=new itemsetnode(cand,0); if (htnf.itemsetlist==null) htnf.itemsetlist=new Vector(); htnf.itemsetlist.addElement(isn); } else { if (htnf.ht==null) htnf.ht=new Hashtable(HT); if (htnf.ht.containsKey(Integer.toString(getitemat(i,cand)))) { htnf=(hashtreenode)htnf.ht.get(Integer.toString(getitemat(i,cand))); genhash(i+1,htnf,cand); } else { hashtreenode htn=new hashtreenode(); htnf.ht.put(Integer.toString(getitemat(i,cand)),htn); if (i==n-1) { htn.nodeattr=IL; //Vector isl=new Vector(); //htn.itemsetlist=isl; genhash(i+1,htn,cand); } else { htn.nodeattr=HT; //Hashtable ht=new Hashtable(); //htn.ht=ht; genhash(i+1,htn,cand); } } } } //end public void genhash(int i, hashtreenode htnf, String cand) //------------------------------------------------------------// Method Name: createlargeitemset // Purpose : find all itemset which have their counters>=minsup // Parameter : int n : n-itemset // Return : //------------------------------------------------------------public void createlargeitemset(int n) { Vector candlist=new Vector(); Vector lis=new Vector(); //large item set hashtreenode htn=new hashtreenode(); int i; // System.out.println("Generating "+n+"-large item set ....");

Dept. Computer Science & Engg.

35

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory candlist=((candidateelement)candidate.elementAt(n-1)).candlist; htn=((candidateelement)candidate.elementAt(n-1)).htroot; getlargehash(0,htn,fullitemset,lis); largeitemset.addElement(lis); } // end public void createlargeitemset(int n) //------------------------------------------------------------// Method Name: getlargehash // Purpose : recursively traverse candidate hash tree // : to find all large itemset // Parameter : htnf is a hashtreenode (when other method call this method,it is the root) // : cand : candidate itemset string // : int i : recursive depth // : Vector lis : Vector that stores large itemsets // Return : //------------------------------------------------------------public void getlargehash(int i,hashtreenode htnf,String transa,Vector lis) { Vector tempvec=new Vector(); int j; if (htnf.nodeattr==IL) { tempvec=htnf.itemsetlist; for (j=1;j<=tempvec.size();j++) if (((itemsetnode)tempvec.elementAt(j-1)).counter >= ((minsup * M) / 100)) lis.addElement( ((itemsetnode)tempvec.elementAt(j-1)).itemset ); } else { if (htnf.ht==null) return; for (int b=i+1;b<=N;b++) if (htnf.ht.containsKey(Integer.toString(getitemat(b,transa)))) getlargehash(b,(hashtreenode)htnf.ht.get(Integer.toString(getitemat(b,transa))),transa,lis); } } //------------------------------------------------------------// Method Name: transatraverse // Purpose : read each transaction, traverse hashtree, // incrment approporiate itemset counter. // Parameter : int n : n-itemset // Return : //------------------------------------------------------------public void transatraverse(int n) { FileInputStream file_in; DataInputStream data_in;

Dept. Computer Science & Engg.

36

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory String oneline=new String(); int i=0,j=0,len=0; String transa; hashtreenode htn=new hashtreenode(); StringTokenizer st; String str0; int numRead=0; //System.out.println("Traverse "+n+"-candidate hashtree ... "); htn=((candidateelement)candidate.elementAt(n-1)).htroot; try { file_in = new FileInputStream(transafile); data_in = new DataInputStream(file_in); while ( true ) { transa=new String(); oneline=data_in.readLine(); numRead++; if ((oneline==null)||(numRead > M)) break; st=new StringTokenizer(oneline.trim()); j=0; while ((st.hasMoreTokens()) && j < N) { j++; str0=st.nextToken(); i=Integer.valueOf(str0).intValue(); if (i!=0) { transa=transa.concat(" "); transa=transa.concat(Integer.toString(j)); len++; } } transa=transa.trim(); transatrahash(0,htn,transa); } } catch (IOException e) { System.out.println(e); } } //------------------------------------------------------------// Method Name: transatrahash // Purpose : called by transatraverse // : recursively traverse hash tree // Parameter : htnf is a hashtreenode (when other method call this method,it is the root) // : cand : candidate itemset string // : int i : recursive depth,from i-th item, recursive // Return : //-------------------------------------------------------------

Dept. Computer Science & Engg.

37

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory public void transatrahash(int i,hashtreenode htnf,String transa) { String stris=new String(); Vector itemsetlist=new Vector(); int j,lastpos,len,d; itemsetnode tmpnode=new itemsetnode(); if (htnf.nodeattr==IL) { itemsetlist=(Vector)htnf.itemsetlist; len=itemsetlist.size(); for (j=0;j<len;j++) { tmpnode=(itemsetnode)itemsetlist.elementAt(j); d=getitemat(htnf.depth,tmpnode.itemset); lastpos=transa.indexOf(Integer.toString(d)); if (lastpos!=-1) ((itemsetnode)(itemsetlist.elementAt(j))).counter++; } return; } else //HT for (int b=i+1;b<=itemsetsize(transa);b++) if (htnf.ht.containsKey(Integer.toString(getitemat(b,transa)))) transatrahash(i,(hashtreenode)htnf.ht.get(Integer.toString(getitemat(b,transa))),transa); } // public transatrahash(int ii,hashtreenode htnf,String transa)

//------------------------------------------------------------// Method Name: aprioriProcess() // Purpose : main processing method // Parameters : // Return : //------------------------------------------------------------public aprioriProcess() throws IOException { candidateelement cande; int k=0; Vector large=new Vector(); Date d=new Date(); long s1,s2; System.out.println(); System.out.println("Algorithm apriori starting now....."); System.out.println(); getconfig();

Dept. Computer Science & Engg.

38

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory

fullitemset=new String(); fullitemset=fullitemset.concat("1"); for (int i=2;i<=N;i++) { fullitemset=fullitemset.concat(" "); fullitemset=fullitemset.concat(Integer.toString(i)); } d=new Date(); s1=d.getTime(); while (true) { k++; cande=new candidateelement(); cande.candlist=createcandidate(k); //System.out.println("C"+k+"("+k+"-candidate-itemset): "+cande.candlist); if (cande.candlist.isEmpty()) break; cande.htroot=null; candidate.addElement(cande); ((candidateelement)candidate.elementAt(k-1)).htroot=createcandidatehashtree(k); //System.out.println("Now reading transactions, increment counters of itemset"); transatraverse(k); createlargeitemset(k); System.out.println("Frequent "+k+"-itemsets:"); System.out.println((Vector)(largeitemset.elementAt(k-1))); } hashtreenode htn=new hashtreenode(); htn=((candidateelement)candidate.elementAt(k-2)).htroot; d=new Date(); s2=d.getTime(); System.out.println(); System.out.println("Execution time is: "+((s2-s1)/1000) + " seconds."); //System.out.println("End."); } }

Dept. Computer Science & Engg.

39

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory

Dept. Computer Science & Engg.

40

SDM College of Engg,Dharwad

Advanced Database Management System Laboratory OUTPUT:

Dept. Computer Science & Engg.

41

SDM College of Engg,Dharwad

Anda mungkin juga menyukai