武汉理工大学面向对象与多线程综合实验——数据库版本

第三次验收:面向对象与多线程综合实验之数据库版本

面向对象与多线程综合实验是一次大项目,总共分为4个部分进行验收,我将分成四个部分展示4个版本的项目工程。希望看到本文章的你,对你有所收获。


档案管理系统简介

档案管理系统:用于规范档案文件管理,构建档案资源信息共享服务平台,为用户提供完整的档案管理和网络查询功能。
• 系统是一个基于C/S的GUI应用程序
• 使用Java SE开发
• 综合运用面向对象编程的相关知识

系统环境

 系统开发环境:JavaSE-12
 集成开发工具:Eclipse Java 2019-06
 GUI开发插件:Window Builder
数据库:MySQL Server 8.0.22+Navicat Premium 12

系统功能

在这里插入图片描述

JDBC(Java DataBase Connectivity)

 为Java应用程序提供了一系列的类,使其能够快速高效地
访问数据库
 这些功能是由一系列的类和接口来完成的,只需使用相关
的对象,即可完成对数据库的操作

JDBC Driver for MySQL

 MySQL Connector/J
下载地址:https://dev.mysql.com/downloads/connector/j/
 属于本地协议驱动(JDBC Type 4 driver)
 需要导入工程Java Build Path


以下是本篇文章正文内容,下面案例可供参考

具体实现

Start.java

package MSystem.GUI;
import java.sql.SQLException;

import MSystem.DataProcessing;



public class Start {
    
    
	public static void main(String args[]) {
    
    
		String driverName="com.mysql.cj.jdbc.Driver";               // 加载数据库驱动类
	    String url="jdbc:mysql://localhost:3306/document?serverTimezone=GMT";       // 声明数据库的URL
	    String user="root";                                      // 数据库用户
	    String password="123456";
		try {
    
    
			DataProcessing.connectToDatabase(driverName, url, user, password);
		} catch (ClassNotFoundException e) {
    
    
			e.printStackTrace();
		} catch (SQLException e) {
    
    
			e.printStackTrace();
		}
		MainGUI.main(null);
	}
}


DataProcessing.java

重点在DataProcessing.java有了很大的不同,数据处理函数须围绕着数据库展开,运用恰当的SQL语言来编写函数。

代码如下(示例):

package MSystem;
import java.util.Enumeration;
import java.util.Hashtable;
import java.sql.*;

public  class DataProcessing {
    
    

	/*private static boolean connectToDB=false;
	
	static Hashtable<String, User> users;
	static Hashtable<String, Doc> docs;

	static {
		users = new Hashtable<String, User>();
		users.put("jack", new Operator("jack","123","operator"));
		users.put("rose", new Browser("rose","123","browser"));
		users.put("kate", new Administrator("kate","123","administrator"));
		Init();
		
		Timestamp timestamp = new Timestamp(System.currentTimeMillis()); 
		docs = new Hashtable<String,Doc>();
		docs.put("0001",new Doc("0001","jack",timestamp,"Doc Source Java","Doc.java"));
		
		
	}
	
	public static  void Init(){
		// connect to database
		
		// update database connection status
//		if (Math.random()>0.2)
//			connectToDB = true;
//		else
//			connectToDB = false;
	}
	
	public static Doc searchDoc(String ID) throws SQLException {
		if (docs.containsKey(ID)) {
			Doc temp =docs.get(ID);
			return temp;
		}
		return null;
	}
	
	public static Enumeration<Doc> getAllDocs() throws SQLException{		
		Enumeration<Doc> e  = docs.elements();
		return e;
	} 
	
	public static boolean insertDoc(String ID, String creator, Timestamp timestamp, String description, String filename) throws SQLException{
		Doc doc;		
	
		if (docs.containsKey(ID))
			return false;
		else{
			doc = new Doc(ID,creator,timestamp,description,filename);
			docs.put(ID, doc);
			return true;
		}
	} 
	
	public static User searchUser(String name) throws SQLException{
//		if ( !connectToDB ) 
//			throw new SQLException( "Not Connected to Database" );
//		double ranValue=Math.random();
//		if (ranValue>0.5)
//			throw new SQLException( "Error in excecuting Query" );
		
		if (users.containsKey(name)) {
			return users.get(name);			
		}
		return null;
	}
	
	public static User search(String name, String password) throws SQLException, IOException {
//		if ( !connectToDB ) 
//	        throw new SQLException( "Not Connected to Database" );
//		double ranValue=Math.random();
//		if (ranValue>0.5)
//			throw new SQLException( "Error in excecuting Query" );
		if (users.containsKey(name)) {
			User temp =users.get(name);
			if ((temp.getPassword()).equals(password))
				return temp;
		}
		return null;
	}
	
	public static Enumeration<User> getAllUser() throws SQLException{
//		if ( !connectToDB ) 
//	        throw new SQLException( "Not Connected to Database" );
//		
//		double ranValue=Math.random();
//		if (ranValue>0.5)
//			throw new SQLException( "Error in excecuting Query" );
		
		Enumeration<User> e  = users.elements();
		return e;
	}
	
	
	
	public static boolean updateUser(String name, String password, String role) throws SQLException{
		User user;
//		if ( !connectToDB ) 
//	        throw new SQLException( "Not Connected to Database" );
//		
//		double ranValue=Math.random();
//		if (ranValue>0.5)
//			throw new SQLException( "Error in excecuting Update" );
		
		if (users.containsKey(name)) {
			if (role.equalsIgnoreCase("administrator"))
				user = new Administrator(name,password, role);
			else if (role.equalsIgnoreCase("operator"))
				user = new Operator(name,password, role);
			else
				user = new Browser(name,password, role);
			users.put(name, user);
			return true;
		}else
			return false;
	}
	
	public static boolean insertUser(String name, String password, String role) throws SQLException{
		User user;
		
//		if ( !connectToDB ) 
//	        throw new SQLException( "Not Connected to Database" );
//		
//		double ranValue=Math.random();
//		if (ranValue>0.5)
//			throw new SQLException( "Error in excecuting Insert" );
		
		if (users.containsKey(name))
			return false;
		else{
			if (role.equalsIgnoreCase("administrator"))
				user = new Administrator(name,password, role);
			else if (role.equalsIgnoreCase("operator"))
				user = new Operator(name,password, role);
			else
				user = new Browser(name,password, role);
			users.put(name, user);
			return true;
		}
	}
	
	public static boolean deleteUser(String name) throws SQLException{
//		if ( !connectToDB ) 
//	        throw new SQLException( "Not Connected to Database" );
//		
//		double ranValue=Math.random();
//		if (ranValue>0.5)
//			throw new SQLException( "Error in excecuting Delete" );
		
		if (users.containsKey(name)){
			users.remove(name);
			return true;
		}else
			return false;
		
	}	
            
	public static void disconnectFromDB() {
		if ( connectToDB ){
			// close Statement and Connection            
			try{
//				if (Math.random()>0.5)
//					throw new SQLException( "Error in disconnecting DB" );      
//			}catch ( SQLException sqlException ){                                            
//			    sqlException.printStackTrace();           
			}finally{                                            
				connectToDB = false;              
			}                             
		} 
   }  */         
	
	private static Connection connection;
	private static Statement statement;
                @SuppressWarnings("unused")
	private static PreparedStatement preparedStatement;
	private static ResultSet resultSet;
	private static boolean connectedToDatabase=false;
	
	public static void connectToDatabase(String driveName,String url,String user,String password) throws ClassNotFoundException, SQLException {
    
    
		Class.forName(driveName);
		connection=DriverManager.getConnection(url, user, password);
        connectedToDatabase=true;
	}
	
	public static void disconnectFromDatabase() {
    
    
		if(connectedToDatabase) {
    
    
			try {
    
    
				resultSet.close();
				statement.close();
				connection.close();
			}catch(SQLException sqlException) {
    
    
				sqlException.printStackTrace();
			}finally {
    
    
				connectedToDatabase=false;
			}
		}
	}
	
	public static Doc searchDoc(String DocID) throws SQLException{
    
    
		Doc temp=null;
		if(!connectedToDatabase) throw new SQLException("Not Connected to Database.");
		
		statement=connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
		String sql="select * from doc_info where Id='"+DocID+"'";
		resultSet=statement.executeQuery(sql);
		
		if(resultSet.next()) {
    
    
			String ID=resultSet.getString("ID");
			String creator=resultSet.getString("creator");
			Timestamp timestamp=resultSet.getTimestamp("timestamp");
			String description=resultSet.getString("description");
			String filename=resultSet.getString("filename");
			temp=new Doc(ID,creator,timestamp,description,filename);
		}
		return temp;
	}
	
	public static Enumeration<Doc> getAllDocs() throws SQLException{
    
    
		Hashtable<String,Doc> docs=new Hashtable<String,Doc>();
		Doc temp=null;
		Enumeration<Doc> e;
		if(!connectedToDatabase) throw new SQLException("Not Connected to Database.");
		
		statement=connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
	    String sql="select * from doc_info";
	    resultSet=statement.executeQuery(sql);
	    
	    while(resultSet.next()) {
    
    
	    	String ID=resultSet.getString("ID");
			String creator=resultSet.getString("creator");
			Timestamp timestamp=resultSet.getTimestamp("timestamp");
			String description=resultSet.getString("description");
			String filename=resultSet.getString("filename");
			temp=new Doc(ID,creator,timestamp,description,filename);
			docs.put(ID, temp);
	    }
	    e=docs.elements();
	    return e;
    }
	
	 public static boolean insertDoc(String ID,String creator,Timestamp timestamp,String description,String filename)throws SQLException{
    
    
		 if(!connectedToDatabase) throw new SQLException("Not Connected to Database.");
		 
		 statement=connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
		 String sql="select * from doc_info where Id='"+ID+"'";
		 resultSet=statement.executeQuery(sql);
		 
	     if(resultSet.next()) return false;
	     sql="insert into doc_info(Id,creator,timestamp,description,filename) values "+"('"+ID+"','"+creator+"','"+timestamp+"','"+description+"','"+filename+"')";
	     if(statement.executeUpdate(sql)>0) return true;
	     else return false;
	 }
	 
	 public static User searchUser(String name) throws SQLException{
    
    
		 User temp=null;
		 
		 if(!connectedToDatabase) throw new SQLException("Not Connected to Database.");
			
		 statement=connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
		 String sql="select * from user_info where username ='"+name+"'";
		 resultSet=statement.executeQuery(sql);
			
		 if(resultSet.next()) {
    
    
			String Name=resultSet.getString("username");
			String password=resultSet.getString("password");
			String role=resultSet.getString("role");
			temp=new User(Name,password,role);
		 }	
		 return temp;
	 }
	 
	 public static User search(String name,String password) throws SQLException{
    
    
		 User temp=null;
		 
		 if(!connectedToDatabase) throw new SQLException("Not Connected to Database.");
		 
		 statement=connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
		 String sql="select * from user_info where username='"+name+"'and password='"+password+"'";
		 resultSet=statement.executeQuery(sql);
		 
		 if(resultSet.next()) {
    
    
			String Name=resultSet.getString("username");
			String Password=resultSet.getString("password");
			String role=resultSet.getString("role");
			temp=new User(Name,Password,role);
		 }
		 return temp;
	 }
	 
	 public static Enumeration<User> getAllUser() throws SQLException{
    
    
		 Hashtable<String,User> users=new Hashtable<String,User>();
		 User temp = null;
		 Enumeration<User> e;
		 if(!connectedToDatabase) throw new SQLException("Not Connected to Database.");
			
		 statement=connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
		 String sql="select * from user_info";
		 resultSet=statement.executeQuery(sql);
		    
		 while(resultSet.next()) {
    
    
			String name=resultSet.getString("username");
			String password=resultSet.getString("password");
			String role=resultSet.getString("role");
			temp=new User(name,password,role);
			users.put(name, temp);
		 }
		 e=users.elements();
		 return e;
	 }
	 
	 public static boolean updateUser(String name,String password,String role) throws SQLException{
    
    
		 if(!connectedToDatabase) throw new SQLException("Not Connected to Database.");
		 
		 statement=connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
		 String sql="select * from user_info where username='"+name+"'";
		 resultSet=statement.executeQuery(sql);
		 
		 if(!resultSet.next()) return false;
		 sql="update user_info set password='"+password+"',role='"+role+"' where username='"+name+"'";
		 if(statement.executeUpdate(sql)>0) return true;
		 else return false;
	 }
	 
	 public static boolean insertUser(String name,String password,String role) throws SQLException{
    
    
		 if(!connectedToDatabase) throw new SQLException("Not Connected to Database.");
		 
		 statement=connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
		 String sql="select * from user_info where username='"+name+"'";
		 resultSet=statement.executeQuery(sql);
		 
		 if(resultSet.next()) return false;
		 sql="insert into user_info(username,password,role) values "+"('"+name+"','"+password+"','"+role+"')";
		 if(statement.executeUpdate(sql)>0) return true;
		 else return false;
	 }
	 
	 public static boolean deleteUser(String name) throws SQLException{
    
    
         if(!connectedToDatabase) throw new SQLException("Not Connected to Database.");
		 
		 statement=connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
		 String sql="select * from user_info where username='"+name+"'";
		 resultSet=statement.executeQuery(sql);
		 
		 if(!resultSet.next()) return false;
		 sql="delete from user_info where username='"+name+"'";
		 if(statement.executeUpdate(sql)>0) return true;
		 else return false;
	 }

	public static String getname(String name) throws SQLException{
    
    
		User temp=null;
		 if(!connectedToDatabase) throw new SQLException("Not Connected to Database.");
		 
		 statement=connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
		 String sql="select * from user_info where username='"+name+"'";
		 resultSet=statement.executeQuery(sql);
		 if(resultSet.next())
		 {
    
    
			String Name=resultSet.getString("username");
			String password=resultSet.getString("password");
			String role=resultSet.getString("role");
			 temp=new User(Name,password,role);
			return temp.getName();
		}
		 	return null;	
		}
		
	
	
	public static String getrole(String name) throws SQLException{
    
    
		User temp=null;
		if(!connectedToDatabase) throw new SQLException("Not Connected to Database.");
		 
		 statement=connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
		 String sql="select * from user_info where username='"+name+"'";
		 resultSet=statement.executeQuery(sql);
		 if(resultSet.next()) {
    
    
				String Name=resultSet.getString("username");
				String password=resultSet.getString("password");
				String role=resultSet.getString("role");
				 temp=new User(Name,password,role);
				return temp.getRole();
			}
			 	return null;
	
	}
	
	/*public static void xuliehua() throws IOException {
		FileOutputStream user = new FileOutputStream("d:\\ch1\\ping\\users.bin\\"); 
		FileOutputStream doc = new FileOutputStream("d:\\ch1\\ping\\doc.bin\\"); 
		ObjectOutputStream s1 = new ObjectOutputStream(user);
		ObjectOutputStream s2 = new ObjectOutputStream(doc);
		s1.writeObject(users);
		s2.writeObject(docs);
		s1.close();
		s2.close();
	}*/
	public static void main(String[] args) {
    
    		

	}
	
}

其他部分变化不大,详情可参考我之前的文章:

面向对象与多线程综合实验——控制台输出版本
面向对象与多线程综合实验——GUI设计版本

总结

数据库版本相较于之前的版本对数据改用了数据库存储,之前结构设计好的,对版本的修改就不会很大,主要完成的任务就是改写数据处理函数。

猜你喜欢

转载自blog.csdn.net/mo_zhe/article/details/112565584