PL I – ASSIGNMENT 13

ASSIGNMENT NO. 13

Title:
Connectivity with MongoDB using any Java application.

Requirements:
1. Computer System with Windows/Linux/Open Source Operating System.
2. JDK
3. Eclipse / Netbeans
4. MongoDB Server and Client

Theory:
MongoDB is a powerful, flexible, and scalable data store. It combines the ability to scale out with many of the most useful features of relational databases, such as secondary indexes, range queries, and sorting. MongoDB is also incredibly featureful: it has tons of useful features such as built-in support for MapReduce-style aggregation and geospatial indexes. MongoDB is a document-oriented database, not a relational one.
Some of the basic concepts of MongoDB:
 A document is the basic unit of data for MongoDB, roughly equivalent to a row in a relational database management system (but much more expressive).
 Similarly, a collection can be thought of as the schema-free equivalent of a table.
 A single instance of MongoDB can host multiple independent databases, each of which can have its own collections and permissions.
 MongoDB comes with a simple but powerful JavaScript shell, which is useful for the administration of MongoDB instances and data manipulation.
 Every document has a special key, “_id”, that is unique across the document’s collection.
To connect database, you need to specify database name, if database doesn’t exist then mongodb creates it automatically.
Code snippets to connect to database would be as follows:

//import required packages
try{
// To connect to mongodb server
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// Now connect to your databases
DB db = mongoClient.getDB( "test" );
System.out.println("Connect to database successfully");
boolean auth = db.authenticate(myUserName, myPassword);
System.out.println("Authentication: "+auth);
}
catch(Exception e){ // catch statement }

Program can be compiled and executed using following commands :
$ javac MongoDBJDBC.java

$ java -classpath “.:mongo-2.10.1.jar” MongoDBJDBC
Connect to database successfully
Authentication: true
Getting/ selecting a collection: To get/select a collection from the database, getCollection() method of com.mongodb.DBCollection class is used.

Following code snippet is useful for creating collection using JAVA.

//creates a collection
DBCollection collection = db.getCollection(“dummyColl”);
//Create object to represent MongoDB document
BasicDBObject doc = new BasicDBObject();
//store key value pairs in document and insert document in database collection.
doc.put(“officer”, “Andrew Smith”);
doc.put(“location”, “Target Shopping Center parking lot”);
doc.put(“vehicle_plate”, “Virginia 2345”);
doc.put(“offense”, “Double parked”);
doc.put(“date”, “2010/08/13”);
doc.put(“pic”, gfsFile);
collection.insert(doc);

After storing documents in database, MongoDB Cursor is used to retrieve stored results and display them.

MongoDB Cursor: In the mongo shell, the primary method for the read operation is
the db.collection.find() method. This method queries a collection and returns a cursor to the returning documents. To access the documents, you need to iterate the cursor. However, in the mongo shell, if the returned cursor is not assigned to a variable using the var keyword, then the cursor is automatically iterated up to 20 times to print up to the first 20 documents in the results. For example, in the mongo shell, the following read operation queries the inventory collection for documents that have type equal to ‘food’ and automatically print up to the first 20 matching documents:

db.inventory.find( { type: ‘food’ } );
Manually Iterate through Cursor: You can also use the cursor method next() to access the
documents, as in the following example:

var myCursor = db.inventory.find( { type: 'food' } );
while (myCursor.hasNext()) {
print(tojson(myCursor.next()));
}

As an alternative print operation, consider the printjson() helper method to

replaceprint(tojson()):
var myCursor = db.inventory.find( { type: 'food' } );
while (myCursor.hasNext()) { printjson(myCursor.next()); }

You can use the cursor method forEach() to iterate the cursor and access the documents, as in the following example:

var myCursor = db.inventory.find( { type: 'food' } );
myCursor.forEach(printjson);

Conclusion : This assignment explains details about storing and retrieving documents in MongoDB using JAVA.

 

***************************PROGRAM  I*****************************

//AIM : Connectivity with MongoDB using any Java application.

import java.net.UnknownHostException;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
public class MongoJava {
public static void main(String args[])
    {
        try
            {
                System.out.println("***********MENU********");
                System.out.println("1. Insert\n2. Delete\n3. Update\n4. Select
                 \n5. Exit\nEnter your Choice\n*********************\n");
          BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
              int choice=Integer.parseInt(br.readLine());
              Mongo mongo = new Mongo("localhost", 27017);
              DB db = mongo.getDB("yourdb");
              // get a single collection
              DBCollection collection = db.getCollection("dummyColl");
                do
                {
               switch(choice)
               {
                   case 1:
                       System.out.println("************INSERT***********");
                       System.out.println("Enter your First name");
                       String fname=br.readLine();
                       System.out.println("Enter your Last name");
                       String lname=br.readLine();
                       System.out.println("Enter your Roll no.");
                       int rno=Integer.parseInt(br.readLine());
                       System.out.println("Enter your Dept no.");
                       int dno=Integer.parseInt(br.readLine());
              BasicDBObject newDocument = new BasicDBObject();
              newDocument.put("Fname",fname);
              newDocument.put("Lname",lname);
              newDocument.put("Rno",rno);
              newDocument.put("DeptNo",dno);
              collection.save(newDocument);
               System.out.println("Document inserted");
               break;
               case 2:
                     System.out.println("************DELETE***********");
                     System.out.println("Enter Roll no. you want to delete");
                     rno=Integer.parseInt(br.readLine());
                     BasicDBObject document = new BasicDBObject();
                     document.put("Rno",rno);
                     collection.remove(document);
                      System.out.println("Document deleted");
                      break;
                      case 3:
                       System.out.println("************UPDATE***********");
                        System.out.println("Enter Roll no. you want to update");
                        rno=Integer.parseInt(br.readLine());
                        System.out.println("Enter new Dept no.");
                        dno=Integer.parseInt(br.readLine());
                         BasicDBObject updateDocument = new BasicDBObject();
    updateDocument.append("$set", new BasicDBObject().append("DeptNo", dno));
    BasicDBObject searchQuery2 = new BasicDBObject().append("Rno", rno);
          collection.update(searchQuery2, updateDocument);
                     System.out.println("Document  updated");
                      break;
                  case 4:
                      System.out.println("************Display***********");
              DBCursor cursor = collection.find();
                   while (cursor.hasNext()) {
                        System.out.println(cursor.next());
                       }
                      break;
                   case 5:
                       System.exit(0);
                       break;
                   default:
                       System.out.println("Please check your choice");
               }                 }while(true);
    }
        catch(Exception e)
        {
            System.out.println(e);
        }
    } }

***************************PROGRAM  II*****************************

AIM : Connectivity with MongoDB using any Java application
 (Created using Netbeans IDE)
//MainClass.java
public class MainClass extends javax.swing.JFrame {
    /**
     * Creates new form MainClass
     */
    public MainClass() {
        initComponents();
    }              
    private void initComponents() {
       jButton1 = new javax.swing.JButton();
       jButton2 = new javax.swing.JButton();
       jLabel1 = new javax.swing.JLabel();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
       jButton1.setText("Store Details");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 150, -1, -1));
       jButton2.setText("Show Details");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 140, -1, -1));
        jLabel1.setFont(new java.awt.Font("Century Schoolbook L", 1, 14)); // NOI18N
        jLabel1.setText("Student Information System");
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 30, 260, 40));
        pack();
    }// </editor-fold>                       
 
   private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
        new StoreDetails().setVisible(true);
    }                                       
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
        new ShowDetails().setVisible(true);
    }                                       
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        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(MainClass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainClass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainClass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainClass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainClass().setVisible(true);
            }
        });
    }
   // Variables declaration - do not modify                    
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    // End of variables declaration                  
}
//StoreDetails.java
import java.io.*;
import java.net.*;
import com.mongodb.*;
public class StoreDetails extends javax.swing.JFrame {
    /**
     * Creates new form StoreDetails
     */
    public StoreDetails() {
        initComponents();
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jTextField3 = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jTextField4 = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jTextField5 = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jTextField6 = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        jTextField7 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
        jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 22)); // NOI18N
        jLabel1.setText("Student Information");
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(102, 0, -1, -1));
        jLabel2.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
        jLabel2.setText("Name");
        getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 46, -1, -1));
        getContentPane().add(jTextField1, new org.netbeans.lib.awtextra.AbsoluteConstraints(104, 45, 255, -1));
        jLabel3.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
        jLabel3.setText("Std");
        getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 91, -1, -1));
        getContentPane().add(jTextField2, new org.netbeans.lib.awtextra.AbsoluteConstraints(104, 90, 84, -1));
        jLabel4.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
        jLabel4.setText("Div");
        getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(219, 91, -1, -1));
        getContentPane().add(jTextField3, new org.netbeans.lib.awtextra.AbsoluteConstraints(279, 90, 80, -1));
        jLabel5.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
        jLabel5.setText("Roll No");
        getContentPane().add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 136, -1, -1));
        getContentPane().add(jTextField4, new org.netbeans.lib.awtextra.AbsoluteConstraints(104, 135, 84, -1));
        jLabel6.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
        jLabel6.setText("Address");
        getContentPane().add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 181, -1, -1));
        getContentPane().add(jTextField5, new org.netbeans.lib.awtextra.AbsoluteConstraints(115, 180, 257, -1));
        jLabel7.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
        jLabel7.setText("City");
        getContentPane().add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 220, -1, -1));
        getContentPane().add(jTextField6, new org.netbeans.lib.awtextra.AbsoluteConstraints(92, 219, 84, -1));
       jLabel8.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
        jLabel8.setText("Pin");
        getContentPane().add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(213, 220, -1, -1));
        getContentPane().add(jTextField7, new org.netbeans.lib.awtextra.AbsoluteConstraints(276, 219, 96, -1));
        jButton1.setBackground(new java.awt.Color(255, 255, 51));
        jButton1.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
        jButton1.setText("Submit");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
           public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(47, 267, 105, -1));
        jButton2.setBackground(new java.awt.Color(255, 255, 51));
        jButton2.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
        jButton2.setText("Reset");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(244, 267, 103, -1));
       pack();
    }// </editor-fold>                       
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
       try
       {
            Mongo mongo = new Mongo("localhost", 27017);
            DB db = mongo.getDB("sis");
            DBCollection collection = db.getCollection("info");
            BasicDBObject document = new BasicDBObject();
            String name=jTextField1.getText();
            String std=jTextField2.getText();
            String div=jTextField3.getText();
            String roll=jTextField4.getText();
            String addr=jTextField5.getText();
            String city=jTextField6.getText();
            String pin=jTextField7.getText();
            document.put("Name",name);
            document.put("Std",std);
            document.put("Div",div);
            document.put("RollNo",roll);
            document.put("Address",addr);
            document.put("City",city);
            document.put("Pin",pin);
            collection.save(document);
            javax.swing.JOptionPane.showMessageDialog(this,"Document Stored Successfully !!");
       }
       catch(Exception e)
        {
            System.out.println(e);
        }
        // TODO add your handling code here:
    }                                       
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
        jTextField1.setText("");
        jTextField2.setText("");
        jTextField3.setText("");
        jTextField4.setText("");
        jTextField5.setText("");
        jTextField6.setText("");
        jTextField7.setText("");
    }                                       
   /**
    * @param args the command line arguments
     */
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;
    private javax.swing.JTextField jTextField6;
    private javax.swing.JTextField jTextField7;
    // End of variables declaration                  
}
 
//ShowDetails.java
import java.io.*;
import java.net.*;
import com.mongodb.*;
public class ShowDetails extends javax.swing.JFrame {
    /**
     * Creates new form StoreDetails
     */
    Mongo mongo;
       DB db;
       DBCollection  collection;
       DBCursor cursor;
    public ShowDetails() {
        initComponents();
       try
        {
         mongo = new Mongo("localhost", 27017);
          db = mongo.getDB("sis");
            collection = db.getCollection("info");
            cursor=collection.find();
         DBObject document = cursor.next();
            jTextField1.setText((String)document.get("Name"));
            jTextField2.setText((String)document.get("Std"));
             jTextField3.setText((String)document.get("Div"));
              jTextField4.setText((String)document.get("RollNo"));
               jTextField5.setText((String)document.get("Address"));
                jTextField6.setText((String)document.get("City"));
                 jTextField7.setText((String)document.get("Pin"));
        }
        catch(Exception e)
        {
            System.out.println(e);
            javax.swing.JOptionPane.showMessageDialog(this,"No More Records");
        }
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {
      jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jTextField3 = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jTextField4 = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jTextField5 = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jTextField6 = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        jTextField7 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
       setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
        jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 22)); // NOI18N
        jLabel1.setText("Student Information");
       getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(102, 0, -1, -1));
        jLabel2.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
        jLabel2.setText("Name");
        getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 46, -1, -1));
        getContentPane().add(jTextField1, new org.netbeans.lib.awtextra.AbsoluteConstraints(104, 45, 255, -1));
       jLabel3.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
        jLabel3.setText("Std");
        getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 91, -1, -1));
        getContentPane().add(jTextField2, new org.netbeans.lib.awtextra.AbsoluteConstraints(104, 90, 84, -1));
        jLabel4.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
        jLabel4.setText("Div");
        getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(219, 91, -1, -1));
        getContentPane().add(jTextField3, new org.netbeans.lib.awtextra.AbsoluteConstraints(279, 90, 80, -1));
        jLabel5.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
        jLabel5.setText("Roll No");
        getContentPane().add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 136, -1, -1));
        getContentPane().add(jTextField4, new org.netbeans.lib.awtextra.AbsoluteConstraints(104, 135, 84, -1));
        jLabel6.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
        jLabel6.setText("Address");
        getContentPane().add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 181, -1, -1));
        getContentPane().add(jTextField5, new org.netbeans.lib.awtextra.AbsoluteConstraints(115, 180, 257, -1));
        jLabel7.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
        jLabel7.setText("City");
        getContentPane().add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 220, -1, -1));
        getContentPane().add(jTextField6, new org.netbeans.lib.awtextra.AbsoluteConstraints(92, 219, 84, -1));
 
        jLabel8.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
        jLabel8.setText("Pin");
        getContentPane().add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(213, 220, -1, -1));
        getContentPane().add(jTextField7, new org.netbeans.lib.awtextra.AbsoluteConstraints(276, 219, 96, -1));
 
        jButton1.setBackground(new java.awt.Color(255, 255, 51));
        jButton1.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
        jButton1.setText("Next");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(47, 267, 105, -1));
       jButton2.setBackground(new java.awt.Color(255, 255, 51));
        jButton2.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
        jButton2.setText("Reset");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(244, 267, 103, -1));
       pack();
    }// </editor-fold>                       
 
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try
        {
           
          DBObject document = cursor.next();
          jTextField1.setText((String)document.get("Name"));
            jTextField2.setText((String)document.get("Std"));
             jTextField3.setText((String)document.get("Div"));
              jTextField4.setText((String)document.get("RollNo"));
               jTextField5.setText((String)document.get("Address"));
                jTextField6.setText((String)document.get("City"));
                 jTextField7.setText((String)document.get("Pin"));
 
        }
        catch(Exception e)
        {
            System.out.println(e);
            javax.swing.JOptionPane.showMessageDialog(this,"No More Records");
        }
        // TODO add your handling code here:
    }                                       
 
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                        
 
        // TODO add your handling code here:
        jTextField1.setText("");
        jTextField2.setText("");
        jTextField3.setText("");
        jTextField4.setText("");
        jTextField5.setText("");
        jTextField6.setText("");
        jTextField7.setText("");
 
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        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(StoreDetails.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(StoreDetails.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);

       } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(StoreDetails.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(StoreDetails.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
 
        /* Create and display the form */

       java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new StoreDetails().setVisible(true);
            }
        });
    }
 
   // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
   private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;
    private javax.swing.JTextField jTextField6;
    private javax.swing.JTextField jTextField7;
    // End of variables declaration                  
}

*************************OUTPUT OF PROGRAM II ************************

Leave a Reply

Your email address will not be published. Required fields are marked *