java rmi数据库_Java RMI数据库应用程序

在上一章中,我们创建了一个RMI图形用户界面应用程序的示例,客户端调用服务器端显示GUI窗口(JavaFX)的方法。

在本章中,我们将以一个例子来看看客户端程序如何检索位于服务器上的MySQL数据库中的表的记录。

假设在数据库:testdb中有一个名称为student的表,其表结构和数据如下所示 –

+----+--------+--------+------------+---------------------+ | ID | NAME | BRANCH | PERCENTAGE | EMAIL | +----+--------+--------+------------+---------------------+ | 1 | Maxsu | IT | 85 | maxsu@yiibai.com | | 2 | Curry | EEE | 95 | curry123@gmail.com | | 3 | Alex | ECE | 90 | alexs130@gmail.com | +----+--------+--------+------------+---------------------+

创建数据库和表如下语句 –

CREATE DATABASE IF NOT EXISTS testdb DEFAULT CHARSET utf8 COLLATE utf8_general_ci; use testdb; -- ---------------------------- -- Table structure for `student` -- ---------------------------- DROP TABLE IF EXISTS `student`; CREATE TABLE `student` ( `id` int(10) NOT NULL AUTO_INCREMENT, `name` varchar(32) NOT NULL DEFAULT '', `branch` varchar(16) NOT NULL DEFAULT '', `percentage` float unsigned DEFAULT '0', `email` varchar(48) NOT NULL DEFAULT '', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of student -- ---------------------------- INSERT INTO `student` VALUES ('1', 'Maxsu', 'IT', '85', 'maxsu@yiibai.com'); INSERT INTO `student` VALUES ('2', 'Curry', 'EEE', '96', 'curry123@gmail.com'); INSERT INTO `student` VALUES ('3', 'Alex', 'ECE', '92', 'alexs130@gmail.com');

假设所使用的MySQL服务器的用户名是:root,其密码是:123456。

创建 Student 类

创建一个Student类,并创建setter和getter方法,创建一个Java源代码文件:Student.java,如下所示。

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

定义远程接口

在这里,我们定义一个名为Hello的远程接口,Hello接口中有一个getStudents()方法。此方法返回一个包含Student类对象的列表。

import java.rmi.Remote; import java.rmi.RemoteException; import java.util.*; // Creating Remote interface for our application public interface Hello extends Remote { public List getStudents() throws Exception; }

开发实现类

创建一个类并实现上面创建的Hello远程接口。

这里我们实现远程接口的getStudents()方法。当调用此方法时,它将检索数据库:students表中的记录。使用Student类的setter方法设置对象的值并返回该对象列表。创建一个JAVA源文件:ImplExample.java 如下所示 –

import java.sql.*; import java.util.*; // Implementing the remote interface public class ImplExample implements Hello { // Implementing the interface method public List getStudents() throws Exception { List list = new ArrayList(); // JDBC driver name and database URL String JDBC_DRIVER = "com.mysql.jdbc.Driver"; String DB_URL = "jdbc:mysql://localhost:3306/testdb"; // Database credentials String USER = "root"; String PASS = "123456"; 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); list.add(student); } rs.close(); return list; } }

服务器程序

RMI服务器程序应实现远程接口或扩展实现类。 在这里,我们将创建一个远程对象并将其绑定到RMI注册表。

以下是本应用程序的服务器程序。 在这里,我们将扩展上述创建的类,创建一个远程对象并使用绑定名称为:hello ,将其注册到RMI注册表。创建一个JAVA源文件:Server.java 如下所示 –

import java.rmi.registry.Registry; import java.rmi.registry.LocateRegistry; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; public class Server extends ImplExample { public Server() {} public 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(); } } }

客户端程序

以下是本应用程序的客户端程序。 在这里,我们获取远程对象并调用getStudents()方法。它从列表对象中检索表 – student的行记录并显示它们。创建一个JAVA源文件:Client.java 如下所示 –

import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.util.*; public class Client { private Client() {} public 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"); // Calling the remote method using the obtained object List list = (List)stub.getStudents(); for (Student s:list)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(list); } catch (Exception e) { System.err.println("Client exception: " + e.toString()); e.printStackTrace(); } } }

运行示例的步骤

以下是运行RMI示例的步骤。

注意:如果手动编译,需要把上面代码存放到目录:F:workspjava_rmijava-dbapp中,并创建一个目录:F:workspjava_rmijava-dbapplibs,把下载的 mysql-connector-java-5.1.40-bin.jar 库(下载地址: )放入到 F:workspjava_rmijava-dbapplibs 目录中。

第一步 – 打开存储所有程序的文件夹,并编译所有Java文件,如下所示。

F:workspjava_rmijava-dbapp> javac -Djava.ext.dirs=F:workspjava_rmijava-dbapplibs *.java

第二步 – 使用以下命令启动rmi注册表。

F:workspjava_rmijava-dbapp> start rmiregistry

执行上面命令后,将在单独的窗口中启动一个rmi注册表。

第三步 – 运行服务器类代码,如下所示。

F:workspjava_rmijava-dbapp>java -Djava.ext.dirs=F:workspjava_rmijava-dbapplibs Server Server ready

第三步 – 运行客户端类文件,如下所示。

F:workspjava_rmijava-dbapp>java -Djava.ext.dirs=F:workspjava_rmijava-dbapplibs Client

执行上面命令后,输出结果如下 –

F:workspjava_rmijava-dbapp>java -Djava.ext.dirs=F:workspjava_rmijava-dbapplibs Client ID: 1 name: Maxsu branch: IT percent: 85 email: maxsu@yiibai.com ID: 2 name: Curry branch: EEE percent: 96 email: curry123@gmail.com ID: 3 name: Alex branch: ECE percent: 92 email: alexs130@gmail.com F:workspjava_rmijava-dbapp>

¥ 我要打赏   纠错/补充 收藏

上一篇: 下一篇:哥,这回真没有了

加QQ群啦,易百教程官方技术学习群

注意:建议每个人选自己的技术方向加群,同一个QQ最多限加 3 个群。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
web报表工具 请移步:http://download.csdn.net/source/2881508 不多说,除了RMI的学习外,gui对新手入门也是个不错的学习 /* *此类适合在本地注册的RMI服务器,避免了使用了多个DOS的写法,只需要简单的给使用 *本类提供的方法即可。 */ package common.rmiserver; import java.rmi.Naming; import java.rmi.NotBoundException; import java.rmi.Remote; import java.rmi.registry.Registry; import java.rmi.registry.LocateRegistry; //import java.rmi.RMISecurityManager; import java.rmi.RemoteException; import java.net.MalformedURLException; import java.rmi.server.UnicastRemoteObject; import common.zip.ZipClientSocketFactory; import common.zip.ZipServerSocketFactory; public final class RMIServer { private Registry registry = null; // @jve:decl-index=0: private String serverName = "RMIServer"; private String serverPath = "localhost"; private int port = 1099; private Remote serverInterface = null; private Boolean isStart = false; private AllFace dataAllFace = null; private int dataPort = 0;// 数据端口,0表示端口由RMI服务器动态生成. private Remote stub; public RMIServer() { } /* * 使用默认端口,默认服务器名称,服务路径构造函数 use the default port,server name and the url */ public RMIServer(Remote obj) { this.serverInterface = obj; } /* * 使用默认端口,服务路径构造函数 use the default port and server url */ public RMIServer(String servername, Remote obj) { this.serverName = servername; this.serverInterface = obj; } /* * 服务器为默认值的构造函数 use the default url */ public RMIServer(String servername, int port, Remote obj) { this.port = port; this.serverName = servername; this.serverInterface = obj; } /* * 适合1.4范围的版本,当然也适合5.0的版本 */ public Boolean setStart() throws RemoteException, MalformedURLException, NotImplementInterfaceException { if (registry == null) registry = LocateRegistry.createRegistry(port); if (serverInterface == null) { throw new NotImplementInterfaceException( "not found the reote interface method!!"); } Naming.rebind("rmi://"+serverPath + ":" + port + "/" + serverName, serverInterface); isStart = true; return isStart; } /* * jdk5.0以后的写法,在使用之前使用setXxx方法给对象赋值 */ public Boolean start() throws RemoteException, MalformedURLException, NotImplementInterfaceException { if(stub==null) stub = (Remote) UnicastRemoteObject.exportObject(dataAllFace, dataPort);// 0表示端口随机生成. if (registry == null) registry = LocateRegistry.createRegistry(port, new ZipClientSocketFactory(), new ZipServerSocketFactory()); setProperty(serverPath); //绑定IP registry.rebind(serverName, stub); isStart = true; return isStart; } /* * 如果有多个ip,则使用这个方法绑定指定的IP */ public void setProperty(String ip) { System.setProperty("java.rmi.server.hostname", ip); } /* * close the server */ public void close() throws RemoteException, MalformedURLException, NotBoundException { //UnicastRemoteObject.unexportObject(dataAllFace, true); Naming.unbind("rmi://"+serverPath + ":" + port + "/" + serverName); isStart = false; } /* * set server name,if not set the name,the service will use the default name * "RMIServer" */ public void setServerName(String serverName) { this.serverName = serverName; } /* * set the server URL,default localhost "rmi://localhost" */ public void setServerPath(String serverPath) { this.serverPath = serverPath; } /* * set the server port default port is 1099. */ public void setPort(int port) { this.port = port; } /* * set then remote implement method */ public void setServerInterface(Remote serverInterface) { this.serverInterface = serverInterface; } /* * set the server Security */ public void setSecurityManager() { /* if (System.getSecurityManager() == null) { try { // java -Djava.security.policy=policy.txt // common.rmiserver.RMIServer System.setSecurityManager(new RMISecurityManager());// 暂时不要安全设置, } catch (java.rmi.RMISecurityException exc) { throw exc; } }*/ } /* * set the remote method */ public void setDataAllFace(AllFace dataAllFace) { this.dataAllFace = dataAllFace; } /* * set the remote dataport */ public void setDataPort(int dataPort) { this.dataPort = dataPort; } // ----------------------------------------------- /* * return the server URL */ public String getServerPatth() { return serverPath; } /* * return remote method */ public Remote getserverInterface() { return serverInterface; } /* * return the server name */ public String getServerName() { return serverName; } /* * return the server use port */ public int getPort() { return port; } /* * return the server then action state */ public Boolean isStart() { return isStart; } /* * return remote method */ public AllFace getDataAllFace() { return dataAllFace; } /* * return remote dataport */ public int getDataPort() { return dataPort; } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值