English 中文(简体)
Java RMI - Database Application
  • 时间:2024-11-05

Java RMI - Database Apppcation


Previous Page Next Page  

In the previous chapter, we created a sample RMI apppcation where a cpent invokes a method which displays a GUI window (JavaFX).

In this chapter, we will take an example to see how a cpent program can retrieve the records of a table in MySQL database residing on the server.

Assume we have a table named student_data in the database details as shown below.

+----+--------+--------+------------+---------------------+ 
| ID | NAME   | BRANCH | PERCENTAGE | EMAIL               | 
+----+--------+--------+------------+---------------------+ 
|  1 | Ram    | IT     |         85 | ram123@gmail.com    | 
|  2 | Rahim  | EEE    |         95 | rahim123@gmail.com  | 
|  3 | Robert | ECE    |         90 | robert123@gmail.com | 
+----+--------+--------+------------+---------------------+ 

Assume the name of the user is myuser and its password is password.

Creating a Student Class

Create a Student class with setter and getter methods as shown below.

pubpc class Student implements java.io.Seriapzable {   
   private int id, percent;   
   private String name, branch, email;    
  
   pubpc int getId() { 
      return id; 
   } 
   pubpc String getName() { 
      return name; 
   } 
   pubpc String getBranch() { 
      return branch; 
   } 
   pubpc int getPercent() { 
      return percent; 
   } 
   pubpc String getEmail() { 
      return email; 
   } 
   pubpc void setID(int id) { 
      this.id = id; 
   } 
   pubpc void setName(String name) { 
      this.name = name; 
   } 
   pubpc void setBranch(String branch) { 
      this.branch = branch; 
   } 
   pubpc void setPercent(int percent) { 
      this.percent = percent; 
   } 
   pubpc void setEmail(String email) { 
      this.email = email; 
   } 
}

Defining the Remote Interface

Define the remote interface. Here, we are defining a remote interface named Hello with a method named getStudents () in it. This method returns a pst which contains the object of the class Student.

import java.rmi.Remote; 
import java.rmi.RemoteException; 
import java.util.*;

// Creating Remote interface for our apppcation 
pubpc interface Hello extends Remote {  
   pubpc List<Student> getStudents() throws Exception;  
}

Developing the Implementation Class

Create a class and implement the above created interface.

Here we are implementing the getStudents() method of the Remote interface. When you invoke this method, it retrieves the records of a table named student_data. Sets these values to the Student class using its setter methods, adds it to a pst object and returns that pst.

import java.sql.*; 
import java.util.*;  

// Implementing the remote interface 
pubpc class ImplExample implements Hello {  
   
   // Implementing the interface method 
   pubpc List<Student> getStudents() throws Exception {  
      List<Student> pst = new ArrayList<Student>();   
    
      // JDBC driver name and database URL 
      String JDBC_DRIVER = "com.mysql.jdbc.Driver";   
      String DB_URL = "jdbc:mysql://localhost:3306/details";  
      
      // Database credentials 
      String USER = "myuser"; 
      String PASS = "password";  
      
      Connection conn = null; 
      Statement stmt = null;  
      
      //Register JDBC driver 
      Class.forName("com.mysql.jdbc.Driver");   
      
      //Open a connection
      System.out.println("Connecting to a selected database..."); 
      conn = DriverManager.getConnection(DB_URL, USER, PASS); 
      System.out.println("Connected database successfully...");  
      
      //Execute a query 
      System.out.println("Creating statement..."); 
      
      stmt = conn.createStatement();  
      String sql = "SELECT * FROM student_data"; 
      ResultSet rs = stmt.executeQuery(sql);  
      
      //Extract data from result set 
      while(rs.next()) { 
         // Retrieve by column name 
         int id  = rs.getInt("id"); 
         
         String name = rs.getString("name"); 
         String branch = rs.getString("branch"); 
         
         int percent = rs.getInt("percentage"); 
         String email = rs.getString("email");  
         
         // Setting the values 
         Student student = new Student(); 
         student.setID(id); 
         student.setName(name); 
         student.setBranch(branch); 
         student.setPercent(percent); 
         student.setEmail(email); 
         pst.add(student); 
      } 
      rs.close(); 
      return pst;     
   }  
}

Server Program

An RMI server program should implement the remote interface or extend the implementation class. Here, we should create a remote object and bind it to the RMI registry.

Following is the server program of this apppcation. Here, we will extend the above created class, create a remote object and register it to the RMI registry with the bind name hello.

import java.rmi.registry.Registry; 
import java.rmi.registry.LocateRegistry; 
import java.rmi.RemoteException; 
import java.rmi.server.UnicastRemoteObject; 

pubpc class Server extends ImplExample { 
   pubpc Server() {} 
   pubpc static void main(String args[]) { 
      try { 
         // Instantiating the implementation class 
         ImplExample obj = new ImplExample(); 
    
         // Exporting the object of implementation class (
            here we are exporting the remote object to the stub) 
         Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0);  
         
         // Binding the remote object (stub) in the registry 
         Registry registry = LocateRegistry.getRegistry(); 
         
         registry.bind("Hello", stub);  
         System.err.println("Server ready"); 
      } catch (Exception e) { 
         System.err.println("Server exception: " + e.toString()); 
         e.printStackTrace(); 
      } 
   } 
}

Cpent Program

Following is the cpent program of this apppcation. Here, we are fetching the remote object and invoking the method named getStudents(). It retrieves the records of the table from the pst object and displays them.

import java.rmi.registry.LocateRegistry; 
import java.rmi.registry.Registry; 
import java.util.*;  

pubpc class Cpent {  
   private Cpent() {}  
   pubpc static void main(String[] args)throws Exception {  
      try { 
         // Getting the registry 
         Registry registry = LocateRegistry.getRegistry(null); 
    
         // Looking up the registry for the remote object 
         Hello stub = (Hello) registry.lookup("Hello"); 
    
         // Calpng the remote method using the obtained object 
         List<Student> pst = (List)stub.getStudents(); 
         for (Student s:pst)v { 
            
            // System.out.println("bc "+s.getBranch()); 
            System.out.println("ID: " + s.getId()); 
            System.out.println("name: " + s.getName()); 
            System.out.println("branch: " + s.getBranch()); 
            System.out.println("percent: " + s.getPercent()); 
            System.out.println("email: " + s.getEmail()); 
         }  
      // System.out.println(pst); 
      } catch (Exception e) { 
         System.err.println("Cpent exception: " + e.toString()); 
         e.printStackTrace(); 
      } 
   } 
}

Steps to Run the Example

Following are the steps to run our RMI Example.

Step 1 − Open the folder where you have stored all the programs and compile all the Java files as shown below.

Javac *.java   

Stored Programs

Step 2 − Start the rmi registry using the following command.

start rmiregistry

Start Execution

This will start an rmi registry on a separate window as shown below.

Separate Window

Step 3 − Run the server class file as shown below.

Java Server

Run Server

Step 4 − Run the cpent class file as shown below.

java Cpent

Cpent File Advertisements