欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

maven实现学生管理系统

程序员文章站 2022-05-06 16:08:36
...

项目结构
maven实现学生管理系统
pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.jd</groupId>
  <artifactId>xueshengguanlixitong</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>xueshengguanli Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
    	<groupId>javax.servlet</groupId>
    	<artifactId>javax.servlet-api</artifactId>
   	 	<version>3.1.0</version>
    	<scope>provided</scope>
	</dependency>
	<dependency>
    	<groupId>log4j</groupId>
    	<artifactId>log4j</artifactId>
    	<version>1.2.17</version>
	</dependency>
	<dependency>
    	<groupId>mysql</groupId>
    	<artifactId>mysql-connector-java</artifactId>
    	<version>6.0.6</version>
	</dependency>
  </dependencies>
  <build>
    <finalName>xueshengguanlixitong</finalName>
  </build>
   <profiles>//以下代码是为了实现lambda表达式的简化
    <profile>   
      <id>jdk1.8</id>    
      <activation>   
          <activeByDefault>true</activeByDefault>    
          <jdk>1.8</jdk>   
      </activation>    
      <properties>   
          <maven.compiler.source>1.8</maven.compiler.source>    
          <maven.compiler.target>1.8</maven.compiler.target>    
          <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>   
      </properties>   
  </profile>
  </profiles>
</project>

工具:
log4j.properties

# DEBUG\u8BBE\u7F6E\u8F93\u51FA\u65E5\u5FD7\u7EA7\u522B\uFF0C\u7531\u4E8E\u4E3ADEBUG\uFF0C\u6240\u4EE5ERROR\u3001WARN\u548CINFO \u7EA7\u522B\u65E5\u5FD7\u4FE1\u606F\u4E5F\u4F1A\u663E\u793A\u51FA\u6765
log4j.rootLogger=DEBUG,Console,RollingFile
#\u5C06\u65E5\u5FD7\u4FE1\u606F\u8F93\u51FA\u5230\u63A7\u5236\u53F0
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern= [%-5p]-[%d{yyyy-MM-dd HH:mm:ss}] -%l -%m%n
#\u5C06\u65E5\u5FD7\u4FE1\u606F\u8F93\u51FA\u5230\u64CD\u4F5C\u7CFB\u7EDFD\u76D8\u6839\u76EE\u5F55\u4E0B\u7684log.log\u6587\u4EF6\u4E2D
log4j.appender.RollingFile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.RollingFile.File=D://log.log
log4j.appender.RollingFile.layout=org.apache.log4j.PatternLayout
log4j.appender.RollingFile.layout.ConversionPattern=%d [%t] %-5p %-40.40c %X{traceId}-%m%n

db.properties:存放连接数据库时的用到的数据,这样修改连接的设备时不需从java文件中修改

db.user_name = root;
db.password = root;
db.url =jdbc:mysql://127.0.0.1:3306/test1;
PropertiesTool:架起DBLink和db.properties之间的桥梁
package com.jd.tool;

	import java.io.IOException;
	import java.io.InputStream;
	import java.util.Properties;

	public class PropertiesTool {

	  private static Properties properties = new Properties();
	  
	  static {
	    InputStream inputStream = PropertiesTool.class.getClassLoader().getResourceAsStream("db.properties");//将db.properties变为javaIO流对象
	    try {
	      properties.load(inputStream);//将inputStream通过 load方法把key
	    } catch (IOException e) {
	      e.printStackTrace();
	    }
	  }
	  
	  public static void main(String [] ages) {
	    String userName = properties.getProperty("db.username");
	    System.out.print(userName);
	  }
	  
	public static String getValue(String key) {
		return properties.getProperty(key);
	}
}
IRowMapper:函数式接口
package com.jd.tool.db.aa;

import java.sql.ResultSet;

	public interface IRowMapper {
		void rowMapper(ResultSet rs);
	}

DBLink:jdbc用到的方法
package com.jd.tool.db.aa;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.log4j.Logger;

import com.jd.tool.PropertiesTool;
/**
 * sql管理工具类
 *
 *  @author SONG
 */

public class DBLink {
	
	private static Logger logger = Logger.getLogger(DBLink.class);
	
	/*try {
		Class.forName("com.mysql.jdbc.Driver");
		String url = "jdbc:mysql://127.0.0.1:3306/test1";
		connection=DriverManager.getConnection(url, "root", "root");
		statement = connection.createStatement();
		long result = statement.executeLargeUpdate(sql);
		statement.close();//如果上面代码出现异常,则该行代码及其下面代码无法执行,所以资源无法释放;比如sql语句语法错误,则statement和connection无法释放
    	connection.close();*/
	
	/**
	 * 获取数据库连接
	 *
	 *@author SONG
	 */
	private static Connection getConnection() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			String userName = PropertiesTool.getValue("db.username");
			String password =PropertiesTool.getValue("db.password");
			String url = PropertiesTool.getValue("db.url");
			return DriverManager.getConnection(url, userName,password);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.debug(e.getMessage(),e);
		}
		return null;
	}
	
	/**
	 * 查询数据
	 *
	 *@author SONG
	 */
	public void select(String sql,IRowMapper rowMapper ) {//接口无法创建对象,所以rowMapper参数一定指向IRowMapper接口实现类对象
		//此处的rowMapper就是一个形参,到时候接口实现类里的实参再传给它
		Connection connection =null;
		Statement statement =null;
		ResultSet resultSet =null;
		
		try {
			
			connection = getConnection();
			statement = connection.createStatement();
			resultSet = statement.executeQuery(sql);
			rowMapper.rowMapper(resultSet);//因为rowMapper参数指向IRowMapper接口实现类对象,所以此处将调用接口实现类中所实现的rowMapper方法  多态
			
			
		} catch (Exception e) {

			logger.debug(e.getMessage(),e);
		}finally {
			close(resultSet,statement,connection);
		}
	}
	
	/**
	 * 查询数据
	 *
	 *@author SONG
	 */
	public void select(String sql,IRowMapper rowMapper, Object ...pramas ) {//接口无法创建对象,所以rowMapper参数一定指向IRowMapper接口实现类对象
		//此处的rowMapper就是一个形参,到时候接口实现类里的实参再传给它
		Connection connection =null;
		Statement statement =null;
		ResultSet resultSet =null;
		PreparedStatement preparedStatement =null;		
		try {			
			connection = getConnection();
			preparedStatement = connection.prepareStatement(sql);//含有?占位符的sql			
			for (int i = 0; i < pramas.length; i++) {
				preparedStatement.setObject(i+1, pramas[i]);//为?赋值
			}		
			resultSet = preparedStatement.executeQuery();
			rowMapper.rowMapper(resultSet);//因为rowMapper参数指向IRowMapper接口实现类对象,所以此处将调用接口实现类中所实现的rowMapper方法  多态						
		} catch (Exception e) {
			logger.debug(e.getMessage(),e);
		}finally {
			close(resultSet,preparedStatement,connection);
		}
	}

	/**
	 * 判断sql语句能否查出数据
	 *
	 *@author SONG
	 */
	public boolean exist(String sql) {//接口无法创建对象,所以rowMapper参数一定指向IRowMapper接口实现类对象
		//此处的rowMapper就是一个形参,到时候接口实现类里的实参再传给它
		Connection connection =null;
		Statement statement =null;
		ResultSet resultSet =null;
		try {
			connection = getConnection();
			statement = connection.createStatement();
			resultSet = statement.executeQuery(sql);
			return resultSet.next();		
		} catch (Exception e) {
			logger.debug(e.getMessage(),e);
		}finally {
			try {
				if(resultSet!=null){
				resultSet.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			close(resultSet,statement,connection);		
		}
		return false;
	}
	
	/**
	 * 判断sql语句能否查出数据
	 *
	 *@author SONG
	 */
	public boolean exist(String sql,Object ...pramas) {//接口无法创建对象,所以rowMapper参数一定指向IRowMapper接口实现类对象
		//此处的rowMapper就是一个形参,到时候接口实现类里的实参再传给它
		Connection connection =null;
		PreparedStatement preparedStatement =null;
		ResultSet resultSet =null;		
		try {			
			connection = getConnection();
			preparedStatement = connection.prepareStatement(sql);//含有?占位符的sql			
			for (int i = 0; i < pramas.length; i++) {
				preparedStatement.setObject(i+1, pramas[i]);//为?赋值
			}		
			resultSet = preparedStatement.executeQuery();			
			return resultSet.next();			
		} catch (Exception e) {
			logger.debug(e.getMessage(),e);
		}finally {
			close(resultSet,preparedStatement,connection);
		}
		return false;
	}
	
	/**
	 * 修改(insert delete update)数据
	 *
	 *@author SONG
	 */
	public boolean update(String sql) {
		Connection connection=null;
		Statement statement=null;
		try {
			connection=getConnection();
			statement = connection.createStatement();
			long result = statement.executeLargeUpdate(sql);			
			return result>0;			
		} catch (Exception e) {			
			logger.debug(e.getMessage(),e);
		}finally {
			close(statement,connection);
		}
		return false;
	}
	
	/**
	 * 修改(insert delete update)数据
	 *
	 *@author SONG
	 */
	public static boolean update(String sql,Object ...pramas) {
		Connection connection=null;
		PreparedStatement preparedStatement=null;
		try {
			connection = getConnection();
			preparedStatement=connection.prepareStatement(sql);//含有?占位符的sql
			for (int i = 0; i < pramas.length; i++) {
				preparedStatement.setObject(i+1, pramas[i]);//为?赋值
			}
		return preparedStatement.executeUpdate()>0;
		}catch(Exception e) {		
			logger.debug(e.getMessage(),e);
		}finally {
			close(preparedStatement,connection);
		}
		return false;			
	}
	
	/**
	 * 释放资源
	 *
	 *@author SONG
	 */
	private static void close(Statement statement,Connection connection) {
		try {
			if(statement!=null) {
			statement.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			if(connection!=null) {			
			connection.close();
			}
		} catch (SQLException e) {
			logger.debug(e.getMessage(),e);
		}	
	}
		
	/**
	 * 释放资源
	 *
	 *@author SONG
	 */
	private static void close(ResultSet resultSet,Statement statement,Connection connection) {
		try {
			if(resultSet!=null){
			resultSet.close();
			}
		} catch (SQLException e) {
			logger.debug(e.getMessage(),e);
		}
		close(statement,connection);	
	}
}

Main:实现功能

package com.jd.client;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

import javax.swing.tree.RowMapper;

import com.jd.tool.db.DBLink;
import com.jd.tool.db.IRowMapper;

public class Main {
	private static IRowMapper rowMapper;

	public static void main(String[] args) {
		System.out.println("*********************************");
		System.out.println("*\t\t\t\t*");
		System.out.println("*\t欢迎使用学生信息管理系统\t*");
		System.out.println("*\t\t\t\t*");
		System.out.println("*********************************");
		while (true) {
			menu();
		}
	}

	static void menu() {
		System.out.println("1、添加学生信息");
		System.out.println("2、删除学生信息");//学号
		System.out.println("3、修改学生信息");//地址传递
		System.out.println("4、查询学生信息");//name
		System.out.println("请输入操作,以Enter键结束:");
		Scanner scanner = new Scanner(System.in);
		int option  = scanner.nextInt();
		switch (option) {
			case 1:{
				System.out.println("请输入学号");
				String id = scanner.next();
				String sql = "select id from user_info where id = ?";
				if (new DBLink().exist(sql,id)) {
					System.out.println("已经有该学号,重新输入");
					return;
				}
				System.out.println("请输入姓名");
				String name = scanner.next();
				System.out.println("请输入电话");
				String mobile = scanner.next();
				System.out.println("请输入地址");
				String address = scanner.next();
				sql = "insert into user_info(id,name,mobile,address) value(?,?,?,?)";
				if (new DBLink().update(sql, id,name,mobile,address)) {
					System.out.println("添加成功");
					return;
				}
				System.out.println("添加失败");
				break;
			}
			case 2:{
				System.out.println("请输入学号");
				String id = scanner.next();
				/*String sql = "select id from user_info where id = ?";
				if (!new DBLink().exist(sql,id)) {
					System.out.println("没有该学号,重新输入");
					return;
				}*///这里如果有该学号,下面一定删除成功,反之一定失败,所以,这个判断可以不要,直接删了
				String sql = "delete from user_info where id = ?";
				if (new DBLink().update(sql,id)) {
					System.out.println("删除成功");
					return;
				}
				System.out.println("删除失败");
				break;
			}
			case 3:{
				System.out.println("请输入学号");
				String id = scanner.next();
				String sql = "select id from user_info where id = ?";
				if (!new DBLink().exist(sql,id)) {
					System.out.println("没有该学号,重新输入");
					return;
				}
				System.out.println("请输入新姓名");
				String name = scanner.next();
				System.out.println("请输入新电话");
				String mobile = scanner.next();
				System.out.println("请输入新地址");
				String address = scanner.next();
				sql="update user_info set name =?,mobile = ?,address = ? where id = ?";
				if (new DBLink().update(sql, name,mobile,address,id)) {
					System.out.println("更改成功");
					return;
				}
				System.out.println("更改失败");
				break;
			}
			case 4:{
				System.out.println("请输入学号");
				final String id = scanner.next();
				String sql = "select id from user_info where id = ?";
				if (!new DBLink().exist(sql,id)) {
					System.out.println("没有该学号,重新输入");
					return;
				}
				sql = "select id,name,mobile,address from user_info where id = ?";
				//lambda表达式简化
				/*class RowMapper implements IRowMapper{
					public void rowMapper(ResultSet rs) {
						try {
							if (rs.next()) {
								String id = rs.getString("id");
								String name = rs.getString("name");
								String mobile = rs.getString("mobile");
								String address = rs.getString("address");
								System.out.println(id+","+name+","+mobile+","+address);
							}
							System.out.println("查询失败");
						} catch (SQLException e) {
							e.printStackTrace();
						}						
					}					
				};
				IRowMapper rowMapper = new RowMapper();
				new DBLink().select(sql,rowMapper,id);*/
				//lambda表达式进一步简化
				/*IRowMapper rowMapper =(rs)->{
					try {
						if (rs.next()) {
							String name = rs.getString("name");
							String mobile = rs.getString("mobile");
							String address = rs.getString("address");
							System.out.println(id+","+name+","+mobile+","+address);
						}
						System.out.println("查询失败");
					} catch (SQLException e) {
						e.printStackTrace();
					}						
				};
				new DBLink().select(sql,rowMapper,id);*/
				
				new DBLink().select(sql,(rs)->{
					try {
						if (rs.next()) {
							String name = rs.getString("name");
							String mobile = rs.getString("mobile");
							String address = rs.getString("address");
							System.out.println(id+","+name+","+mobile+","+address);
						}
						System.out.println("查询失败");
					} catch (SQLException e) {
						e.printStackTrace();
					}						
				},id);
				break;
			}
			default:
				System.out.println("I'm Sorry,there is not the "+option+" option,please try again.");
		}
	}
}

相关标签: java