0


【Java:JDBC+MySQL实现学生信息管理系统】

此次使用Java JDBC+MySQL数据库实现一个简易的学生管理系统(没有前端界面)。

目录


前言

Java数据库连接,(Java Database Connectivity,简称JDBC)是Java语言中用来规范客户端程序如何来访问数据库的应用程序接口,提供了诸如查询和更新数据库中数据的方法。JDBC也是Sun Microsystems的商标。我们通常说的JDBC是面向关系型数据库的。摘自百度百科–jdbc


现使用JDBC+MySQL实现简易的学生信息管理系统,主要设计学生信息查询、添加学生、修改学生信息、删除学生等功能。

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

一、数据库设计

在StuMIS数据库中创建如下表格:
学生信息表
SQL代码如下:

createdatabase StuIMS defaultCHARACTERset utf8mb4;-- 创建数据库use StuIMS;-- 创建学生表createtable Student(
    studentID char(8)notnullprimarykey,-- 学号
    studentName varchar(30)notnull,-- 姓名
    studentSex char(4)notnulldefault'男',-- 性别
    studentBirthday datenotnulldefault'2002-1-1',-- 出生日期
    credit intnotnulldefault0,-- 学分
    studentClass char(6)notnull-- 班级编号)

数据库创建完成后,向数据表中添加部分测试数据,代码如下:

insertinto 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');

二、Java代码编写实现

1.创建项目,引入JDBC的.jar包

下载数据库的驱动包,可以到官网下载:驱动下载
在这里插入图片描述
下载完成后,将压缩包解压到桌面。
使用eclipse创建一个名为Student的java项目,点击项目右键,找到Build Path—>>Configure Path…
在这里插入图片描述
在这里插入图片描述
点击添加.jar包,找到刚刚解压的文件,选择拓展名为(.jar)的文件。
在这里插入图片描述
点击添加,应用即可。
添加完成后,在项目中新建MainTest类,用于编写Java代码。

2.创建连接驱动方法

在MainTest中创建public Connection getConnection()方法,用于创建数据库的链接驱动。(信息的添加、删除、修改、查询都需要连接数据库,创建连接方法,可以减少代码的冗余。)
代码如下(示例):

publicConnectiongetConnection()throwsSQLException,ClassNotFoundException{StringDriver="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("数据库连接失败。");returnnull;}else{System.out.println("连接成功。");return con;}}

该处使用的url网络请求的数据。

3、查询所有数据


定义SelectAll()方法查询所有学生数据。
代码示例如下:

publicvoidSelectAll()throwsClassNotFoundException,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、插入学生数据

定义public int insertStudent(int num)方法向数据库中添加数据。int num为一次添加的学生的数量。
实例代码如下:

publicintinsertStudent(int num)throwsClassNotFoundException,SQLException{Connection con =getConnection();String sql ="insert into Student values(?,?,?,?,0,'202105')";//定义SQl语句,班级编号和学分不需手动插入。PreparedStatement ps = con.prepareStatement(sql);//执行SQL语句Scanner sc =newScanner(System.in);int count=0;//定义变量保存修改的行数for(int i=1;i<=num;i++){System.out.println("请输入第"+i+"个学生的学号:");StringID= 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、修改学生信息

定义public int updateStudent(String ID)方法,根据学号(唯一,不可重复)修改学生数据信息。
示例代码如下:

publicintupdateStudent(StringID)throwsClassNotFoundException,SQLException{Connection con =getConnection();String sql="update Student set studentName=?,studentSex=?,studentBirthday=? where studentID="+ID;//定义SQL语句修改信息,允许修改的字段值为姓名、性别、出生日期,学号不允许修改。PreparedStatement ps = con.prepareStatement(sql);Scanner sc =newScanner(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、删除学生数据

定义public int deleteStudentByID(String ID)方法删除学生。根据学号执行删除操作。
示例代码如下:

publicintdeleteStudentByID(StringID)throwsClassNotFoundException,SQLException{Connection con =getConnection();Scanner sc =newScanner(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("删除取消。");return0;}}else{System.out.println("信息有误,请重新选择......");return-1;}}

7、menu方法

定义public int menu()方法打印菜单选项。
示例代码如下:

publicintmenu(){Scanner sc =newScanner(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、main方法

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

总结

以上就是学生管理系统的全部内容,其中有部分功能并未完全实现,例如插入学生数据时,并未控制事务的提交,某一条数据插入失败时,之前的数据也会自动提交,逻辑上还不是很完整,如果有感兴趣的朋友可以自行进行完善。删除数据和修改数据时逻辑也还有欠缺。
码字不易,感谢阅读。
完整代码奉上:

packagetest;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.PreparedStatement;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.util.Scanner;@SuppressWarnings("resource")publicclassMainTest{publicstaticvoidmain(String[] args)throwsClassNotFoundException,SQLException{MainTest m =newMainTest();Scanner sc =newScanner(System.in);while(true){int ch = m.menu();switch(ch){case1:m.SelectAll();break;case2:System.out.println("请输入需要添加的学生的数量:");int n = sc.nextInt();int countInsert = m.insertStudent(n);if(countInsert==n){System.out.println("学生信息添加成功!");}else{System.out.println("信息输入有误,学生添加失败。");}break;case3:System.out.println("请输入需要修改的学生的学号:");StringIDUpdate= sc.next();int countUpdate = m.updateStudent(IDUpdate);if(countUpdate>0){System.out.println("学生信息修改成功。");}break;case4:System.out.println("请输入需要删除的学生的学号:");StringIDDelete= sc.next();int countDelete = m.deleteStudentByID(IDDelete);if(countDelete>0){System.out.println("删除成功。");}else{System.out.println("删除失败。");}break;case5:System.out.println("感谢使用,系统退出中......");;System.exit(0);default:System.err.println("请选择相应的功能......");}System.out.println("请输入回车键继续......");
            sc.nextLine();}}publicintmenu(){Scanner sc =newScanner(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();}//    连接数据库publicConnectiongetConnection()throwsSQLException,ClassNotFoundException{StringDriver="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("数据库连接失败。");returnnull;}else{System.out.println("连接成功。");return con;}}//    查询所有数据publicvoidSelectAll()throwsClassNotFoundException,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");}}//    插入数据publicintinsertStudent(int num)throwsClassNotFoundException,SQLException{Connection con =getConnection();String sql ="insert into Student values(?,?,?,?,?,'202105')";PreparedStatement ps = con.prepareStatement(sql);Scanner sc =newScanner(System.in);int count=0;for(int i=1;i<=num;i++){System.out.println("请输入第"+i+"个学生的学号:");StringID= 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;}//    修改数据publicintupdateStudent(StringID)throwsClassNotFoundException,SQLException{Connection con =getConnection();String sql="update Student set studentName=?,studentSex=?,studentBirthday=? where studentID="+ID;PreparedStatement ps = con.prepareStatement(sql);Scanner sc =newScanner(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;}publicintdeleteStudentByID(StringID)throwsClassNotFoundException,SQLException{Connection con =getConnection();Scanner sc =newScanner(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;}}}
标签: java mysql 数据库

本文转载自: https://blog.csdn.net/qq_43884946/article/details/127552152
版权归原作者 toMontain 所有, 如有侵权,请联系我们删除。

“【Java:JDBC+MySQL实现学生信息管理系统】”的评论:

还没有评论