利用JAVA+MySQL实现学生选课系统

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/Bazingaea/article/details/52653129

 

一个简单的学生选课系统,先说一下思路:

首先需要选择身份,学生或者是管理员,如果选择管理员需要输入密码,菜单上的选项有的只能管理员访问

比如创建菜单,有的只能学生访问,比如选课和创建学生。

 

如果选择了非可选的选项,则会提示不可选,然后重新选择

 

 

OPTION 1 2 

创建学生,创建课程,都会将数据保存在数据库中

 

 

OPTION 3 4

得到学生列表和课程列表都是从数据库中获取数据

 

 

OPTION 5 6

登陆会从数据库中校验用户名和密码,修改密码也会同时修改数据库的密码

 

通过ID,USERNAME,PASSWORD登录

密码默认为12345,可以选择更改密码,若登陆失败会重新登陆

 

 

OPTION 7

若选择学生选课,在选课之前需要先登陆

 

 

选课:会先显示出已经选择的课程,然后在从课程列表中选择新的课程

 

OPTION 8 退出系统

 

 

 

 

 

数据表:一共4张

学生表,课程表,按照实体类的的成员属性来存储字段类型

登陆表,存放学生登陆的用户名和密码

学生选课表,存放学生选择的课程

 

 

 

 

 

 

 

 

 

 

代码实现:

有两个实体类,分别为课程类和学生类,采用javabean模式,比较简单就不贴代码了,只贴出成员变量

 

 

 

一个工具类,封装了获得与数据库连接的Connection对象的方法

 

package wwy.bjsxt.chooseCourse;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBUtil {
	private static final String URL="jdbc:mysql://127.0.01:3306/test";
	private static final String USER="root";
	private static final String PASSWORD="depp";

	private static Connection conn = null;

	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(URL, USER, PASSWORD);

		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	public static Connection getConnection(){
		return conn;
	}
}

 

 

 

 

 

 

 

接下来就是核心代码,Mytest2类,略多

 

package wwy.bjsxt.chooseCourse;

/**
 * 学生选课
 * @author wwyDEPP
 */

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;

public class MyTest2 {
	private static Scanner console = new Scanner(System.in);
	private static String managerPass = "management";
	private static Connection conn = DBUtil.getConnection();
	private static List<Course> stuCourseList = new ArrayList<Course>();
	private static Map<Integer, Course> courseList = new HashMap<Integer, Course>();

	public static void main(String[] args) {
		System.out.println("Welcome to choose you own courses!\n"
				+ "Only management can choose option 2 and 3.\n"
				+ "And only student can choose option 5 and 6.");
		showMenu();

	}

	
	/**
	 * 显示选项
	 */
	public static void showMenu() {
		System.out.println("--------------------OPTIONS---------------------");
		System.out.println("1.Create Student");
		System.out.println("2.Create Course");
		System.out.println("3.Get Student List");
		System.out.println("4.Get Course List");
		System.out.println("5.Student Login");
		System.out.println("6.Change Password");
		System.out.println("7.Student Choose Course");
		System.out.println("8.EXIT");

		managerTest();
	}

	
	/**
	 * 检测是否为管理员
	 */
	private static void managerTest() {
		System.out.println("Are you management or student? 1/0");
		int info = console.nextInt();
		if (info == 1) {
			System.out.println("Please input you management password:");
			String password = console.next();

			if (password.equals(managerPass)) {
				System.out.println("--------------Management-----------------");
				getMenuForManager();
			} else {
				System.out.println("You password is wrong!");
			}
		} else if (info == 0) {
			System.out.println("-----------------Student------------------");
			getMenuForStu();
		} else {
			System.out.println("Please input 0/1 ,try again!");
			managerTest();
		}
	}
	

	/**
	 * 管理员菜单
	 */
	private static void getMenuForManager() {
		
		System.out.println("Please input you option number:");
		int info= console.nextInt();
		do {
			switch (info) {
			case 1:
				createStudent();
				break;
			case 2:
				createCourse();
				break;
			case 3:
				getStudentList();
				break;
			case 4:
				getCourseList();
				break;
			case 5:
				System.out.println("You cannt choose this option!Please try angin!");
				getMenuForManager();
				break;
			case 6:
				changePassword();
				break;
			case 7:
				System.out.println("You cannt choose this option!Please try angin!");
				getMenuForManager();
				break;
			case 8:
				System.exit(0);
				break;
			default:
				System.out.println("Please input the right number! TRY AGAIN!");
			}
			
			System.out.println("Do you want to choose other option? ");
			info = console.nextInt();
			
		} while (info != 8);
	}
	

	/**
	 * 学生菜单
	 */
	private static void getMenuForStu() {

		System.out.println("Please input you option number:");
		int info = console.nextInt();
		do {
			switch (info) {
			case 1:
				createStudent();
				break;
			case 2:
				System.out.println("You cannt choose this option!Please try angin!");
				getMenuForStu();
				break;
			case 3:
				System.out.println("You cannt choose this option!Please try angin!");
				getMenuForStu();
				break;
			case 4:
				getCourseList();
				break;
			case 5:
				studentLogin();
				break;
			case 6:
				changePassword();
				break;
			case 7:
				studentChooseCourse();
				break;
			case 8:
				System.exit(0);
				break;
			default:
				System.out.println("Please input the right number!TRY AGAIN!");
			}

			System.out.println("Do you want to choose other option? ");
			info = console.nextInt();
		} while (info != 8);
	}

	
	/**
	 * 学生登录
	 */
	public static String studentLogin() {
		
		boolean flag;

		System.out.println("-----------------LOGIN---------------");

		System.out.println("Please input you userid:");
		int stuID = console.nextInt();
		System.out.println("Please input you username:\n");

		String stuName = console.next();
		System.out.println("Please input you password:"
				+ "TIPS:If you donot change you password it will be 12345!");
		String stuPassword = console.next();

		String name = null, password = null;
		Statement stmt;
		ResultSet rs;

		try {
			stmt = conn.createStatement();
			rs = stmt.executeQuery("SELECT * FROM login WHERE id=" + stuID);
			while (rs.next()) {
				name = rs.getString("stuName");
				password = rs.getString("stuPassword");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		if (stuName.equals(name) && stuPassword.equals(password)) {
			System.out.println("login success!");
			flag=true;

		} else {
			System.out.println("there is a mistake with you username or password!");
			flag=false;
		}
		return stuID+","+flag;
	}

	
	/**
	 * 修改登录密码
	 */
	public static void changePassword() {
		System.out.println("Please input you name:");
		String name = console.next();
		System.out.println("Please input new password:");
		String newPassword = console.next();
		//注意SQL语句中的字符串要写在单引号之间,否则会报错
		String sql = " " + "UPDATE login SET stuPassword=" + "'" + newPassword
				+ "' WHERE stuName=" + "'" + name + "'";
		PreparedStatement ptmt;
		try {
			ptmt = conn.prepareStatement(sql);
			ptmt.execute();
			System.out.println("Change password success!");
			System.out.println("Please relogin in !");
			studentLogin();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	

	/**
	 * 判断是否已经登陆 以防还未登陆就进行选课
	 */
	public static void studentChooseCourse() {
		String info=studentLogin();
		while(true){
			String[] infos=info.split(",");
			String flag =infos[1];
			int stuID =Integer.parseInt(infos[0]);
			if (flag.equals("false")) {
				System.out.println("Please login first!");
				info=studentLogin();
			} else {
				studentChooseCourse(stuID);
			}
		}

	}

	
	/**
	 * 学生选课
	 */
	private static void studentChooseCourse(int stuID) {
		System.out.println("-------------Student Choose Course--------------");
		getStuCourses(stuID);
		getCourseList();

		int flag = 1;
		do {
			System.out.println("Please input Course id :");
			int couID = console.nextInt();

			Set<Integer> keySet = courseList.keySet();
			Iterator<Integer> keyIt = keySet.iterator();
			while (keyIt.hasNext()) {

				if (couID == keyIt.next()) {

					Course c = courseList.get(couID);
					stuCourseList.add(c);
				}
			}

			System.out.println("Do you want choose more class? 0/1");
			flag = console.nextInt();
		} while (flag == 1);

		saveDataToMysql(stuID);
	}
	

	/**
	 * 将学生的选课保存到数据库中
	 */
	private static void saveDataToMysql(int stuId) {
		String sql = "INSERT stucourses(stuID,couID) VALUES(" + stuId + ",?)";
		PreparedStatement ptmt = null;

		try {
			ptmt = conn.prepareStatement(sql);

			for (Course c : stuCourseList) {
				System.out.println("b");
				ptmt.setInt(1, c.getId());
				ptmt.execute();
			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	

	/**
	 * 从数据库中得到学生已经选择的课
	 */
	private static void getStuCourses(int stuID) {
		System.out.println("******************************************");
		System.out.println("Here is some courses you already choose:");

		Statement stmt = null;
		ResultSet rs = null;

		try {
			stmt = conn.createStatement();
			rs = stmt.executeQuery("SELECT * FROM courses AS c INNER JOIN stucourses AS s" +
					" ON s.stuID="+ stuID + " WHERE s.couID=c.couID;");
			while (rs.next()) {
				Course course = new Course();
				course.setId(rs.getInt("couId"));
				course.setName(rs.getString("couName"));
				course.setTeacher(rs.getString("couTeacher"));

				System.out.println(course.toString());
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	
	/**
	 * 从数据库中获取学生集合
	 */
	public static void getStudentList() {
		System.out.println("**************************************");
		System.out.println("Here is ALL Students List:");

		Statement stmt = null;
		ResultSet rs = null;

		try {
			stmt = conn.createStatement();
			rs = stmt.executeQuery("select * from students");

			while (rs.next()) {

				Student student = new Student();
				student.setId(rs.getInt("stuID"));
				student.setName(rs.getString("stuName"));
				student.setYear(rs.getString("stuYear"));
				student.setNumber(rs.getString("stuNumber"));
				student.setSex(rs.getString("stuSex"));

				System.out.println(student.toString());
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	
	/**
	 * 从数据库中获取课程列表集合
	 */
	public static void getCourseList() {

		System.out.println("*************************************************");
		System.out.println("Please choose you own course from those follow courses:");

		Statement stmt = null;
		ResultSet rs = null;
		try {
			stmt = conn.createStatement();
			rs = stmt.executeQuery("select * from courses");

			while (rs.next()) {
				Course course = new Course();
				course.setId(rs.getInt("couID"));
				course.setName(rs.getString("couName"));
				course.setTeacher(rs.getString("couTeacher"));

				courseList.put(course.getId(), course);

				System.out.println(course.toString());
			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	
	/**
	 * 课程集合 将课程集合保存在数据库中
	 */
	private static void setCourseList(Course course) {

		courseList.put(course.getId(), course);

		String sql = "" + "INSERT courses (couID,couName,couTeacher) "
				+ "VALUES(?,?,?)";

		try {
			PreparedStatement ptmt = conn.prepareStatement(sql);
			ptmt.setInt(1, course.getId());
			ptmt.setString(2, course.getName());
			ptmt.setString(3, course.getTeacher());

			ptmt.execute();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	
	/**
	 * 学生集合 将学生集合保存在数据库中
	 */
	private static void setStudentList(Student student) {

		String sql = ""+ "INSERT students (stuID,stuName,stuYear,stuNumber,stuSex) "
				+ "VALUES(?,?,?,?,?)";

		String sql2 = "INSERT login (stuName,stuPASSWORD) VALUES(?,12345)";

		PreparedStatement ptmt;
		try {
			ptmt = conn.prepareStatement(sql);
			ptmt.setInt(1, student.getId());
			ptmt.setString(2, student.getName());
			ptmt.setString(3, student.getYear());
			ptmt.setString(4, student.getNumber());
			ptmt.setString(5, student.getSex());

			ptmt.execute();

			ptmt = conn.prepareStatement(sql2);
			ptmt.setString(1, student.getName());
			ptmt.execute();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	
	/**
	 * 创建课程对象 添加到课程集合 添加到数据库中
	 */
	public static void createCourse() {
		System.out.println("-------------------Create Course-----------------");
		System.out.println("Please input course id:");
		int couId = console.nextInt();
		System.out.println("Please input course name:");
		String couName = console.next();
		System.out.println("Please input course teacher:");
		String couTeacher = console.next();

		Course course = new Course(couId, couName, couTeacher);
		System.out.println("create course success!");

		setCourseList(course);
	}
	

	/**
	 * 创建一个学生对象 添加到学生集合 添加到数据库中
	 */
	public static void createStudent() {
		System.out.println("----------------Create Student-----------------");
		System.out.println("Please input student id:");
		int stuID = console.nextInt();
		System.out.println("Please input student name:");
		String stuName = console.next();
		System.out.println("Please input student year:");
		String stuYear = console.next();
		System.out.println("Please input student number:");
		String stuNumber = console.next();
		System.out.println("Please input student sex:");
		String stuSex = console.next();

		System.out.println("create student success!");

		Student student = new Student(stuName, stuID, stuYear, stuNumber,
				stuSex);

		setStudentList(student);
	}
}

 

 

 

 

 

 

大部分代码都是练打字的,实际运行中出现的逻辑错误也容易改正,遇到的一个问题是

只有在已经登陆的前提下,才可以进行选课,选课时必须保证选的是登陆的这个同学的课表

那么就需要从登陆这个方法中,返回两个值,其一是是否登陆成功的判断值,其二是学生的ID号

但是java又无法提供两个返回值,于是博主想了两个办法

 

第一种,创建一个类封装这两个属性,登陆方法返回一个该类的对象

 

第二种,也就是代码中采用的一种,将学生ID和判断值用“,”连接在一起,构成一个字符串

在判断是否登陆的方法中,进行解析字符串,分离出这两个值

 

 

 

小总结:由于博主没想明白整个系统是怎样工作的,直接就啪啪趴敲代码,数据表也是半路准备好了,

这样思路不明确,就开始写,使得整个过程非常混乱,在写选课的时候,才意识到需要登录这个步骤,

来确保每个学生个体选择自己的课程,创建一张新表保存登陆信息,更改密码,等等。

不断的运行使代码更加合理,提示更加清晰。

希望能改正,想明白再动手!自勉!

展开阅读全文

没有更多推荐了,返回首页