[Java: JDBC+MySQL realizes student information management system]

This time, a simple student management system (without a front-end interface) is implemented using the Java JDBC+MySQL database.


foreword

Java Database Connectivity (JDBC for short) is an application programming interface used in the Java language to standardize how client programs access the database, and provides methods such as querying and updating data in the database. JDBC is also a trademark of Sun Microsystems. The JDBC we usually say is oriented to relational databases. Excerpted from Baidu Encyclopedia – jdbc


Now use JDBC+MySQL to implement a simple student information management system, mainly designing student information query, adding students, modifying student information, deleting students and other functions.
提示:以下是本篇文章正文内容,下面案例可供参考

1. Database design

Create the following table in the StuMIS database:
Student Information Form
The SQL code is as follows:

create database StuIMS default CHARACTER set utf8mb4;-- 创建数据库
use StuIMS; 
-- 创建学生表
create table Student(
	studentID char(8) not null primary key, -- 学号
	studentName varchar(30) not null, -- 姓名
	studentSex char(4) not null default '男', -- 性别
	studentBirthday date not null default '2002-1-1', -- 出生日期
	credit int not null default 0, -- 学分
	studentClass char(6) not null -- 班级编号
)

After the database is created, add some test data to the data table, the code is as follows:

insert into Student values('20210101','张三',default,default,0,'202101'),
('20210122','李明',default,'2003-9-15',0,'202101'),
('20210203','王敏','女','2003-6-25',0,'202102'),
('20210218','刘洋',default,'2002-7-08',0,'202102'),
('20210310','刘洋','女','2003-1-29',0,'202103'),
('20210405','江民',default,'2000-12-29',0,'202104'),
('20210436','王军',default,'2002-10-10',0,'202104'),
('20210501','李玉军',default,default,0,'202105'),
('20210502','王红娟','女','2004-1-1',0,'202105');

Two, Java code writing and implementation

1. Create a project and import the .jar package of JDBC

To download the driver package of the database, you can download it from the official website: Driver
insert image description here
Download After the download is complete, decompress the compressed package to the desktop.
Use eclipse to create a java project named Student, right-click on the project, find Build Path—>>Configure Path...
insert image description here
insert image description here
click to add the .jar package, find the file you just decompressed, and select the file with the extension (.jar).
insert image description here
Click Add to apply.
After the addition is complete, create a new MainTest class in the project for writing Java code.

2. Create a connection driver method

Create a public Connection getConnection () method in MainTest to create a database link driver. (The addition, deletion, modification, and query of information all need to connect to the database, and creating a connection method can reduce code redundancy.)
The code is as follows (example):

public Connection getConnection() throws SQLException, ClassNotFoundException {
    
    
		String Driver = "com.mysql.cj.jdbc.Driver";
		String url="jdbc:mysql://localhost:3306/StuIMS";
		String user="root";
		String pwd="123456";
		Class.forName(Driver);//加载驱动
		Connection con = DriverManager.getConnection(url,user,pwd);//建立连接
		if(con.isClosed()) {
    
    
			System.err.println("数据库连接失败。");
			return null;
		}else {
    
    
			System.out.println("连接成功。");
			return con;
		}
	}

The data requested by the url network used here.

3. Query all data


Define the SelectAll () method to query all student data.
The code example is as follows:

public void SelectAll() throws ClassNotFoundException, SQLException {
    
    
		Connection con = getConnection();//调用getConnection()方法获取数据库连接对象
		PreparedStatement ps = con.prepareStatement("select * from Student");//创建预处理对象执行SQL查询语句
		ResultSet rs = ps.executeQuery();//查询结果集
		System.out.println("  学号\t\t姓名\t  性别\t    生日\t\t学分");
		while(rs.next()) {
    
    //遍历结果集
			//使用ResultSet的get方法获取集合中的值,参数为数据库中的字段名
			System.out.println(rs.getString("studentID")+"\t"+rs.getString("studentName")+"\t  "+rs.getString("studentSex")+"\t  "
					+rs.getString("studentBirthday")+"\t"+rs.getString("credit")+"\t");
		}
	}

4. Insert student data

Define the public int insertStudent ( int num ) method to add data to the database. int num is the number of students added at one time.
The example code is as follows:

public int insertStudent(int num) throws ClassNotFoundException, SQLException {
    
    
		Connection con = getConnection();
		String sql = "insert into Student values(?,?,?,?,0,'202105')";//定义SQl语句,班级编号和学分不需手动插入。
		PreparedStatement ps = con.prepareStatement(sql);//执行SQL语句
		Scanner sc = new Scanner(System.in);
		int count=0;//定义变量保存修改的行数
		for(int i=1;i<=num;i++) {
    
    
			System.out.println("请输入第"+i+"个学生的学号:");
			String ID = sc.next();
			System.out.println("请输入第"+i+"个学生的姓名:");
			String name = sc.next();
			System.out.println("请输入第"+i+"个学生的性别:");
			String sex = sc.next();
			System.out.println("请输入第"+i+"个学生的生日:");
			String birthday = sc.next();
			//将输入的值传入,执行SQL,添加数据
			ps.setString(1, ID);
			ps.setString(2, name);
			ps.setString(3, sex);
			ps.setString(4, birthday);
			//executeUpdate()方法的返回值为受影响的行数(插入的数据行数),如果返回值为1,则表示数据插入成功(一次循环执行一次插入)
			if(ps.executeUpdate()==1) {
    
    //
				count++;//插入成功,将count值加一
			}else {
    
    
				System.out.println("数据插入失败。");
				break;
			}
		}
		return count;//返回受影响的行数
	}

5. Modify student information

Define the public int updateStudent ( String ID ) method to modify student data information according to the student ID ( unique, non-repeatable ).
The sample code is as follows:

public int updateStudent(String ID) throws ClassNotFoundException, SQLException {
    
    
		Connection con = getConnection();
		String sql="update Student set studentName=?,studentSex=?,studentBirthday=? where studentID="+ID;
		//定义SQL语句修改信息,允许修改的字段值为姓名、性别、出生日期,学号不允许修改。
		PreparedStatement ps = con.prepareStatement(sql);
		Scanner sc = new Scanner(System.in);
		int count=0;
		System.out.println("请输入学生的姓名:");
		String name = sc.next();
		System.out.println("请输入学生的性别:");
		String sex = sc.next();
		System.out.println("请输入学生的生日:");
		String birthday = sc.next();
		ps.setString(1, name);
		ps.setString(2, sex);
		ps.setString(3, birthday);
		count = ps.executeUpdate();
		return count;//返回受影响的行数
	}

6. Delete student data

Define the public int deleteStudentByID(String ID) method to delete students. Perform the delete operation based on the student ID.
The sample code is as follows:

public int deleteStudentByID(String ID) throws ClassNotFoundException, SQLException {
    
    
		Connection con = getConnection();
		Scanner sc = new Scanner(System.in);
		PreparedStatement psS = con.prepareStatement("select * from Student where studentID="+ID);
		ResultSet rs = psS.executeQuery();
		//根据学号查询需要删除的学生的信息
		System.out.println("即将删除的学生的信息:");
		System.out.println("  学号\t\t姓名\t  性别\t    生日\t\t学分");
		while(rs.next()) {
    
    
			System.out.println(rs.getString("studentID")+"\t"+rs.getString("studentName")+"\t  "+rs.getString("studentSex")+"\t  "
					+rs.getString("studentBirthday")+"\t"+rs.getString("credit")+"\t");
		}
		System.out.println("请确认信息是否无误(y/Y)?");
		char ch1 = sc.next().charAt(0);
		//
		if(ch1=='Y'||ch1=='y') {
    
    
			System.out.println("请确认是否删除(y/Y)?");
			char ch2 = sc.next().charAt(0);
			if(ch2=='y'||ch2=='Y') {
    
    //确认删除后,执行删除操作
				PreparedStatement psD = con.prepareStatement("delete from Student where studentID="+ID);
				int  count  = psD.executeUpdate();
				return count;//返回受影响的行数
			}else {
    
    
				System.out.println("删除取消。");
				return 0;
			}
		}else {
    
    
			System.out.println("信息有误,请重新选择......");
			return -1;
		}
		
	}

7. menu method

Define the public int menu () method to print menu options.
The sample code is as follows:

public int menu() {
    
    
		Scanner sc = new Scanner(System.in);
		System.out.println("******************************欢迎使用学生信息管理系统******************************");
		System.out.println("\t\t功能列表如下:");
		System.out.println("\t\t1、查询学生信息。");
		System.out.println("\t\t2、添加学生信息。");
		System.out.println("\t\t3、修改学生信息。");
		System.out.println("\t\t4、删除学生信息。");
		System.out.println("\t\t5、退出系统。");
		System.out.println("请选择你需要的功能:");
		return sc.nextInt();
	}

8. The main method

public static void main(String[] args) throws ClassNotFoundException, SQLException {
    
    
		MainTest m = new MainTest();//实例化当前类的对象,调用其他成员方法
		Scanner sc = new Scanner(System.in);
		while(true) {
    
    
			int ch = m.menu();//调用菜单选项,获取用户的选择
			switch(ch) {
    
    //使用Switch结构根据用户输入执行不同功能
			case 1:m.SelectAll();break;//查询所有信息
			case 2:
				System.out.println("请输入需要添加的学生的数量:");
				int n = sc.nextInt();
				int countInsert = m.insertStudent(n);//获取插入成功的数据行数
				//如果插入成功行数与用户输入相等,则表示成功。还有事务回滚和提交操作没有实现,感兴趣的朋友可以自行添加实现这个功能。
				if(countInsert==n) {
    
    
					System.out.println("学生信息添加成功!");
				}else {
    
    
					System.out.println("信息输入有误,学生添加失败。");
				}
				break;
			case 3:
				System.out.println("请输入需要修改的学生的学号:");
				String IDUpdate= sc.next();
				int countUpdate = m.updateStudent(IDUpdate);
				if(countUpdate==1) {
    
    //学号唯一,一个学号对应一条数据
					System.out.println("学生信息修改成功。");
				}
				break;
			case 4:
				System.out.println("请输入需要删除的学生的学号:");
				String IDDelete = sc.next();
				int countDelete = m.deleteStudentByID(IDDelete);
				if(countDelete==1) {
    
    
					System.out.println("删除成功。");
				}else {
    
    
					System.out.println("删除失败。");
				}
				break;
			case 5:
				System.out.println("感谢使用,系统退出中......");
				System.exit(0);//退出执行
			default:System.err.println("请选择相应的功能......");
			}
			System.out.println("请输入回车键继续......");
			sc.nextLine();
		}
	}

Summarize

The above is the entire content of the student management system. Some of the functions have not been fully realized. For example, when inserting student data, the submission of transactions is not controlled. When a piece of data fails to be inserted, the previous data will be automatically submitted. Logically, it is not Very complete, if interested friends can improve it by themselves. There is also a lack of logic when deleting data and modifying data.
Code words are not easy, thanks for reading.
Here is the complete code:

package test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

@SuppressWarnings("resource")
public class MainTest {
    
    

	public static void main(String[] args) throws ClassNotFoundException, SQLException {
    
    
		MainTest m = new MainTest();
		Scanner sc = new Scanner(System.in);
		while(true) {
    
    
			int ch = m.menu();
			switch(ch) {
    
    
			case 1:m.SelectAll();break;
			case 2:
				System.out.println("请输入需要添加的学生的数量:");
				int n = sc.nextInt();
				int countInsert = m.insertStudent(n);
				if(countInsert==n) {
    
    
					System.out.println("学生信息添加成功!");
				}else {
    
    
					System.out.println("信息输入有误,学生添加失败。");
				}
				break;
			case 3:
				System.out.println("请输入需要修改的学生的学号:");
				String IDUpdate= sc.next();
				int countUpdate = m.updateStudent(IDUpdate);
				if(countUpdate>0) {
    
    
					System.out.println("学生信息修改成功。");
				}
				break;
			case 4:
				System.out.println("请输入需要删除的学生的学号:");
				String IDDelete = sc.next();
				int countDelete = m.deleteStudentByID(IDDelete);
				if(countDelete>0) {
    
    
					System.out.println("删除成功。");
				}else {
    
    
					System.out.println("删除失败。");
				}
				break;
			case 5:System.out.println("感谢使用,系统退出中......");;System.exit(0);
			default:System.err.println("请选择相应的功能......");
			}
			System.out.println("请输入回车键继续......");
			sc.nextLine();
		}
	}
	public int menu() {
    
    
		Scanner sc = new Scanner(System.in);
		System.out.println("******************************欢迎使用学生信息管理系统******************************");
		System.out.println("\t\t功能列表如下:");
		System.out.println("\t\t1、查询学生信息。");
		System.out.println("\t\t2、添加学生信息。");
		System.out.println("\t\t3、修改学生信息。");
		System.out.println("\t\t4、删除学生信息。");
		System.out.println("\t\t5、退出系统。");
		System.out.println("请选择你需要的功能:");
		return sc.nextInt();
	}
//	连接数据库
	public Connection getConnection() throws SQLException, ClassNotFoundException {
    
    
		String Driver = "com.mysql.cj.jdbc.Driver";
		String url="jdbc:mysql://localhost:3306/StuIMS";
		String user="root";
		String pwd="123456";
		Class.forName(Driver);
		Connection con = DriverManager.getConnection(url,user,pwd);
		if(con.isClosed()) {
    
    
			System.err.println("数据库连接失败。");
			return null;
		}else {
    
    
			System.out.println("连接成功。");
			return con;
		}
		
	}
//	查询所有数据
	public void SelectAll() throws ClassNotFoundException, SQLException {
    
    
		Connection con = getConnection();
		PreparedStatement ps = con.prepareStatement("select * from Student");
		ResultSet rs = ps.executeQuery();
		System.out.println("  学号\t\t姓名\t  性别\t    生日\t\t学分");
		while(rs.next()) {
    
    
			System.out.println(rs.getString("studentID")+"\t"+rs.getString("studentName")+"\t  "+rs.getString("studentSex")+"\t  "
					+rs.getString("studentBirthday")+"\t"+rs.getString("credit")+"\t");
		}
	}
//	插入数据
	public int insertStudent(int num) throws ClassNotFoundException, SQLException {
    
    
		Connection con = getConnection();
		String sql = "insert into Student values(?,?,?,?,?,'202105')";
		PreparedStatement ps = con.prepareStatement(sql);
		Scanner sc = new Scanner(System.in);
		int count=0;
		for(int i=1;i<=num;i++) {
    
    
			System.out.println("请输入第"+i+"个学生的学号:");
			String ID = sc.next();
			System.out.println("请输入第"+i+"个学生的姓名:");
			String name = sc.next();
			System.out.println("请输入第"+i+"个学生的性别:");
			String sex = sc.next();
			System.out.println("请输入第"+i+"个学生的生日:");
			String birthday = sc.next();
			System.out.println("请输入第"+i+"个学生的学分:");
			int credit = sc.nextInt();
			ps.setString(1, ID);
			ps.setString(2, name);
			ps.setString(3, sex);
			ps.setString(4, birthday);
			ps.setInt(5, credit);
			if(ps.executeUpdate()>0) {
    
    
				count++;
			}else {
    
    
				System.out.println("数据插入失败。");
				break;
			}
		}
		return count;
	}
//	修改数据
	public int updateStudent(String ID) throws ClassNotFoundException, SQLException {
    
    
		Connection con = getConnection();
		String sql="update Student set studentName=?,studentSex=?,studentBirthday=? where studentID="+ID;
		PreparedStatement ps = con.prepareStatement(sql);
		Scanner sc = new Scanner(System.in);
		int count=0;
		System.out.println("请输入学生的姓名:");
		String name = sc.next();
		System.out.println("请输入学生的性别:");
		String sex = sc.next();
		System.out.println("请输入学生的生日:");
		String birthday = sc.next();
//		System.out.println("请输入学生的学分:");
//		int credit = sc.nextInt();
		ps.setString(1, name);
		ps.setString(2, sex);
		ps.setString(3, birthday);
//		ps.setInt(4, credit);
		count = ps.executeUpdate();
		return count;
	}
	public int deleteStudentByID(String ID) throws ClassNotFoundException, SQLException {
    
    
		Connection con = getConnection();
		Scanner sc = new Scanner(System.in);
		PreparedStatement psS = con.prepareStatement("select * from Student where studentID="+ID);
		ResultSet rs = psS.executeQuery();
		System.out.println("即将删除的学生的信息:");
		System.out.println("  学号\t\t姓名\t  性别\t    生日\t\t学分");
		while(rs.next()) {
    
    
			System.out.println(rs.getString("studentID")+"\t"+rs.getString("studentName")+"\t  "+rs.getString("studentSex")+"\t  "
					+rs.getString("studentBirthday")+"\t"+rs.getString("credit")+"\t");
		}
		System.out.println("请确认信息是否无误(y/Y)?");
		char ch1 = sc.next().charAt(0);
		if(ch1=='Y'||ch1=='y') {
    
    
			System.out.println("请确认是否删除(y/Y)?");
			char ch2 = sc.next().charAt(0);
			if(ch2=='y'||ch2=='Y') {
    
    
				PreparedStatement psD = con.prepareStatement("delete from Student where studentID="+ID);
				int  count  = psD.executeUpdate();
				return count;
			}else {
    
    
				System.out.println("删除取消。");
				return -1;
			}
		}else {
    
    
			System.out.println("信息有误,请重新选择......");
			return -1;
		}
		
	}
}












Guess you like

Origin blog.csdn.net/qq_43884946/article/details/127552152