(解析+源码)基于JAVA Swing+MySQL实现学生信息管理系统(增、删、改、查)数据库/文件存储
根据学校对学生信息日常管理需要,学生信息管理系统包括以下功能:
- 登录系统;
- 新建学生信息:添加学生信息;
- 删除学生信息:对指定学生信息进行删除;
- 修改学生信息:对指定学生信息进行修改
- 查找学生信息:输入名字关键字、学号、政治面貌等查询符合条件的学生;
- 退出系统。
用户登录后可以对学生信息进行增、删、改、查操作,通过数据库或者文件存储用户录入的信息。
一、功能模块划分
图1 功能模块划分图
二、数据库结构描述
2.1 数据库E-R模型
图2 登录E-R图
图3 学生E-R图
2.2 数据库关系模型--二维表
表1 登录用户名和密码
字段 |
数据类型 |
说明 |
Username |
varchar |
用户名 |
Password |
varchar |
登录密码 |
图4 录入信息后的用户名和密码
表2 学生信息表
字段 |
数据类型 |
说明 |
id |
int |
编号 |
name |
varchar |
姓名 |
sex |
varchar |
性别 |
telephone |
varchar |
联系方式 |
number |
varchar |
学号 |
birthday |
varchar |
出生日期 |
note |
varchar |
政治面貌 |
图5 录入信息后的学生信息表
三、系统详细设计
3.1系统执行流程
图6 系统执行流程图
3.2类的划分
表3
类名 |
类的成员属性和方法 |
说明 |
Connect. java |
private static String driverName |
driverName |
private static String url |
url |
|
private static String userName,private static String password |
用户名和密码 |
|
private Connection conn |
Connection对象 |
|
private Statement stmt |
Statement对象 |
|
public Connect() |
加载数据库 |
|
public Connection getConnection() throws SQLException |
获取数据库连接 |
表4
类名 |
类的成员属性和方法 |
说明 |
StudentSystem.java |
JButton searchBtn, createBtn, updateBtn, deleteBtn,exitBtn |
定义5个系统功能按钮,用于事件响应 |
JTable infoTable |
定义5个表格,用于显示学生信息 |
|
JLabel keyLab |
定义1个标签,用于提醒用户输入信息 |
|
JTextField keyText |
定义1个文本框,用于用户查询信息 |
|
private Map<String, String> PersonInfo |
私有化Map集合对象 |
|
public StudentSystem() |
在面板中添加组件、标签和文本框 |
|
public static void flashInfo() |
将学生信息写入数据库 |
|
public void actionPerformed(ActionEvent e) |
功能按钮监听 |
|
protected void searchInfo(String key) |
实现查询信息 |
|
public static Vector<String> column |
实例化用于存储表格数据的Vector数组 |
|
public static Vector<Vector<String>> info = new Vector<Vector<String>>() |
实例化用于存储学生信息的Vector数 |
表5
类名 |
类的成员属性和方法 |
说明 |
Login. java |
public void showUI |
登录界面按钮、标签和组件 |
button.addMouseListener(new MouseAdapter() |
内部类用于监听用户鼠标事件 |
表6
类名 |
类的成员属性和方法 |
说明 |
MyDialog.java |
private JPanel pCenter, pSouth |
定义2个面板 |
private JLabel nameLab, sexLab, mailLab, birthLab, phoneLab,noteLab |
定义6个学生信息标签,用于提示 |
|
private JTextField nameText, mailText, birthText, phoneText,noteText |
定义6个学生信息文本框用于输入信息 |
|
private JComboBox<String> sex |
定义1个下拉列表组件 |
|
private JButton yesBtn, noBtn |
定义2个按钮,用于给用户选择储存方式 |
|
public MyDialog(String title, Map<String, String> info) |
构造方法,用于窗口添加组件和标案等 |
|
public void actionPerformed(ActionEvent e) |
系统功能按钮监听器模块 |
|
public void insertPerson() |
添加信息当用户输入无效信息时提示模块 |
|
public void dbinsertPerson() |
将新建的学生信息写入数据库的表中模块 |
|
public void fileinsertPerson() |
将新建的学生信息写入文件中模块 |
|
public void deletePerson() |
删除指定学生信息模块 |
|
public void updatePerson() |
修改指定学生信息模块 |
四、各个模块实现方法
4.1 连接数据库
与创建的数据库进行连接,实现步骤如下:
- 加载jdbc驱动程序;
- 创建数据库的连接;
- 创建Statement、Connect;
- 执行SQL语句;
代码:
public class Connect {private static String driverName="com.mysql.cj.jdbc.Driver";private static String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf8&ServerTimezone=GMT&useSSL=false&serverTimezone=UTC";private static String userName = "root";private static String password = "111111";private Connection conn;private Statement stmt;public Connect() {try {Class.forName(driverName);//加载数据库} catch (ClassNotFoundException e) {e.printStackTrace();}}public Connection getConnection() throws SQLException {return DriverManager.getConnection(url, userName, password);//使用DriverManger获取数据库连接}public void dispose() {try {if (conn != null) {conn.close();}if (stmt != null) {stmt.close();}} catch (SQLException e) {e.printStackTrace();}}
}
4.2 登录界面
用户登录界面由JFrame窗口和JLable、JPanel、JTextField等组件构成,通过鼠标事件监听器进行登录,实现方法如下:
- 定义输入用户名和密码所需文本框以及提示组件;
- 创建按钮和鼠标事件监听器;
- 获取数据库用户资料并判断用户名和密码是否正确;
- 显示主界面进行增、删、改、查操作;
运行结果:
图7 登录界面
图8 程序判断用户名和密码是否正确
代码:
public class Login {public static void main(String args[]) {Login l=new Login();//实例化Login对象l.showUI();}public void showUI() {JFrame login=new JFrame();//创建一个JFrame容器窗口login.setTitle("登录系统");//设置标题login.setSize(340,240);//设置窗口大小login.setDefaultCloseOperation(3);//0-DO_NITHING窗口无法关闭;1-HIDE隐藏程序界面但没有关闭程序;2-DISPOSE自动隐藏释放窗体,继续运行应用程序;3-EXITlogin.setLocationRelativeTo(null);//设置窗口位置相对于指定组件的位置login.setResizable(false);//设置窗口不可被调整大小,布尔值//FlowLayout fl=new FlowLayout(FlowLayout.CENTER,5,5);login.setLayout(new FlowLayout());//FloeLayout默认居中对齐,水平、垂直间距默认为5个单位login.setVisible(true);//窗体可见//用户名标签组件JLabel labname=new JLabel();labname.setText("用户名:");labname.setPreferredSize(new Dimension(60, 60));//设置最适合窗口的位置(setPreferredSize)和JLable标签组件的宽度和高度(Dimension)login.add(labname);//加入JFrame窗口JTextField textname=new JTextField();//创建一个JTextField文本框用于输入用户名textname.setPreferredSize(new Dimension(250, 30));login.add(textname);//加入到JFrame窗口中//密码标签组件JLabel labpassword=new JLabel();labpassword.setText("密 码:");labpassword.setPreferredSize(new Dimension(60, 60));login.add(labpassword);JPasswordField jp=new JPasswordField();jp.setPreferredSize(new Dimension(250, 30));login.add(jp);//登录按钮JButton button=new JButton();button.setText("登录"); button.setPreferredSize(new Dimension(100, 40));login.add(button);login.setVisible(true);//为登录键添加鼠标事件监听器button.addMouseListener(new MouseAdapter() {public void mouseClicked(MouseEvent e) {Connect dbconn = new Connect();//实例化Connect对象Statement stmt = null;ResultSet rs = null;try {//用于创建一个 Statement 对象,封装 SQL 语句发送给数据库,通常用来执行不带参数的 SQL 语句stmt = dbconn.getConnection().createStatement();//select * from查询在数据库中表内信息rs = stmt.executeQuery("select * from my_address_login where username='"+textname.getText()+"' and password='"+jp.getText()+"'");if (rs.next()) {new StudentSystem();//主界面login.dispose();//释放界面窗口占用的屏幕资源}else{JOptionPane.showMessageDialog(null, "用户名或密码不正确!!!","提示",2);//java弹窗
JOptionPane.showMessageDialog(null, "提示内容" ,"标题", -1~3);}rs.close();} catch (SQLException e1) {e1.printStackTrace();//在命令行打印异常信息在程序中出错的位置及原因,显示出更深的调用信息//System.out.println(e1);} finally {try {if (stmt != null) {stmt.close();}if (rs != null) {rs.close();}} catch (SQLException e1) {e1.printStackTrace();}}}});}
}
4.3 主界面
主界面由JFrame窗口和JLable、JPanel、JTextField等组件构成,通过鼠标、键盘事件监听器进行功能选项和信息录入,实现方法如下:
- 定义输入信息和功能选择所需文本框以及按钮;
- 创建键盘和鼠标事件监听器;
- 根据用户选择执行对应模块。
运行结果:
图9 主界面
代码:
public StudentSystem() {PersonInfo = new HashMap<String, String>();//数组和链表的结合体,HashMap底层就是一个数组结构,数组中的每一项又是一个链表。新建一个HashMap的时候,就会初始化一个数组Font font = new Font("宋体", Font.PLAIN, 15);//设置字体,类型和大小;Front.PLAIN普通,Front.BLOD加粗,Front.ITALIC斜体JPanel pNorth = new JPanel();pNorth.setLayout(new FlowLayout(FlowLayout.RIGHT));keyLab = new JLabel("请输入关键字:");keyText = new JTextField(10);//搜索文本框//创建系统功能按钮searchBtn = new JButton("搜索学生信息");createBtn = new JButton("新增学生信息");updateBtn = new JButton("修改学生信息");deleteBtn = new JButton("删除学生信息");exitBtn = new JButton("退出系统");//设置字体大小keyLab.setFont(font);searchBtn.setFont(font); createBtn.setFont(font); updateBtn.setFont(font); deleteBtn.setFont(font);exitBtn.setFont(font);//添加监听器searchBtn.addActionListener(this);createBtn.addActionListener(this);updateBtn.addActionListener(this);deleteBtn.addActionListener(this);exitBtn.addActionListener(this);//在JPanel面板的上方加入搜索功能所需的一系列组件pNorth.add(keyLab);pNorth.add(keyText);pNorth.add(searchBtn);//在JPanel面板下方加入系统功能组件JPanel pSouth = new JPanel();pSouth.add(createBtn);pSouth.add(updateBtn);pSouth.add(deleteBtn);pSouth.add(exitBtn);//表格数据column = new Vector<String>();column.add("编号");column.add("姓名");column.add("性别");column.add("电话");column.add("学号");column.add("生日");column.add("政治面貌");flashInfo();//将数据存入数据库infoTable = new JTable(info, column);TableColumn column1 = infoTable.getColumnModel().getColumn(0);column1.setPreferredWidth(30);//自适应TableColumn column3 = infoTable.getColumnModel().getColumn(2);column3.setPreferredWidth(30);//自适应JScrollPane pCenter = new JScrollPane(infoTable);//创建垂直滚动面板this.add(pNorth, "North");this.add(pCenter, "Center");this.add(pSouth, "South");this.setTitle("学生信息管理系统");this.setSize(800, 450);this.setVisible(true);this.setLocationRelativeTo(null);this.setResizable(false);this.setDefaultCloseOperation(EXIT_ON_CLOSE);}public static void flashInfo() {Connect dbconn = new Connect();Statement stmt = null;ResultSet rs = null;info.clear();try {stmt = dbconn.getConnection().createStatement();//创建一个 Statement 对象,封装 SQL 语句发送给数据库rs = stmt.executeQuery("select * from my_address_book");//下达命令执行查询语句并且存放在ResultSet对象中while (rs.next()) {Vector<String> row = new Vector<String>();row.add(rs.getString(1));row.add(rs.getString(2));row.add(rs.getString(3));row.add(rs.getString(4));row.add(rs.getString(5));row.add(rs.getString(6));row.add(rs.getString(7));info.add(row);}rs.close();} catch (SQLException e) {e.printStackTrace();//在命令行打印异常信息在程序中出错的位置及原因} finally {try {if (stmt != null) {stmt.close();}if (rs != null) {rs.close();}} catch (SQLException e) {e.printStackTrace();}}}
4.4 新建学生信息
新建学生信息界面,通过模式对话,即通过JDialog对话框来实现,实现方法如下:
- 定义表格所需集合;
- 定义一个用于连接数据库的对象;
- 定义新建学生信息的相关组件;
- 把组件添加到窗体;
- 调用新建学生信息界面的方法;
- 调用数据库连接;
- 录入学生信息;
- 选择储存方式;
- 判断信息是否正确;
- 完成相应功能。
运行结果:
图10 新建学生信息界面
代码:
public void dbinsertPerson(){//将新建的学生信息写入数据库的表中boolean flag=true;String sql = "insert into my_address_book(name, sex, telephone, number, birthday, note)value(?,?,?,?,?,?)";try {PreparedStatement pstmt = dbconn.getConnection().prepareStatement(sql);pstmt.setString(1, nameText.getText());pstmt.setString(2, (String) sex.getSelectedItem());pstmt.setString(3, phoneText.getText());pstmt.setString(4, mailText.getText());pstmt.setString(5, birthText.getText());pstmt.setString(6, noteText.getText());pstmt.executeUpdate();} catch (SQLException e) {e.printStackTrace();JOptionPane.showMessageDialog(null, "新建联系人失败!");//提示弹窗flag = false;} finally {dispose();if (flag) {JOptionPane.showMessageDialog(null, "新建联系人成功!");//提示弹窗}StudentSystem.flashInfo();//将数据写入数据库DefaultTableModel model = new DefaultTableModel(StudentSystem.info, StudentSystem.column);StudentSystem.infoTable.setModel(model);TableColumn column1 = StudentSystem.infoTable.getColumnModel().getColumn(0);column1.setMaxWidth(40);column1.setMinWidth(40);TableColumn column3 = StudentSystem.infoTable.getColumnModel().getColumn(2);column3.setMaxWidth(40);column3.setMinWidth(40);}}public void fileinsertPerson(){//将新建的学生信息写入文件中boolean flag=true;try {StringBuffer sbf=new StringBuffer();sbf.append(nameText.getText()).append(" ").append((String) sex.getSelectedItem()).append(" ").append(phoneText.getText()).append(" ").append(mailText.getText()).append(" ").append(birthText.getText()).append(" ").append(noteText.getText());File file = new File("information.txt");FileOutputStream fos = null;if(!file.exists()){file.createNewFile();//如果文件不存在,创建该文件fos = new FileOutputStream(file);//首次写入获取}else{//如果文件已存在,就在文件末尾追加写入fos = new FileOutputStream(file,true);}OutputStreamWriter osw = new OutputStreamWriter(fos, "gbk");//指定以UTF-8格式写入文件osw.write(sbf.toString());osw.write("\r\n");osw.close();} catch (Exception e) {e.printStackTrace();JOptionPane.showMessageDialog(null, "新建联系人失败!");//提示弹窗flag = false;} finally {dispose();if (flag) {JOptionPane.showMessageDialog(null, "新建联系人成功!");//提示弹窗}}}
4.5 删除学生信息
删除学生信息界面,通过模式对话,即通过JDialog对话框来实现,实现方法如下:
- 选择删除对象
- 调用数据库连接;
- 删除学生信息;
- 完成相应功能。
运行结果:
图11 未选择删除对象提示信息
图12 删除成功提示
图13 删除指定对象信息后返回主界面
代码:
public void deletePerson() {//删除信息String sql = "delete from my_address_book where id=?";try {
PreparedStatement pstmt = dbconn.getConnection().prepareStatement(sql);pstmt.setString(1, id);pstmt.executeUpdate();} catch (SQLException e) {e.printStackTrace();} finally {dispose();StudentSystem.flashInfo();DefaultTableModel model = new DefaultTableModel(StudentSystem.info, StudentSystem.column);StudentSystem.infoTable.setModel(model);TableColumn column1 = StudentSystem.infoTable.getColumnModel().getColumn(0);column1.setMaxWidth(40);column1.setMinWidth(40);TableColumn column3 = StudentSystem.infoTable.getColumnModel().getColumn(2);column3.setMaxWidth(40);column3.setMinWidth(40);}}
4.6 修改学生信息
修改学生信息界面,通过模式对话,即通过JDialog对话框来实现,实现方法如下:
- 定义修改叙述信息的相关组件;
- 加载数据库,获得选中的那一行的所有信息;
- 把组件添加到窗体;
- 调用修改学生信息界面的方法;
- 修改学生信息;
- 完成相应功能。
运行结果:
图14 未选择修改对象程序提示
图15 修改指定对象信息界面
代码:
public void updatePerson() {//修改信息if (nameText.getText().isEmpty()) {JOptionPane.showMessageDialog(null, "请输入姓名!");}String sql = "update my_address_book set name=?,sex=?,telephone=?,number=?,birthday=?,note=? where id=?";try { PreparedStatement pstmt = dbconn.getConnection().prepareStatement(sql);pstmt.setString(1, nameText.getText());pstmt.setString(2, (String) sex.getSelectedItem());pstmt.setString(3, phoneText.getText());pstmt.setString(4, mailText.getText());pstmt.setString(5, birthText.getText());pstmt.setString(6, noteText.getText());pstmt.setString(7, id);pstmt.executeUpdate();} catch (SQLException e) {e.printStackTrace();} finally {dispose();StudentSystem.flashInfo();DefaultTableModel model = new DefaultTableModel(StudentSystem.info, StudentSystem.column);StudentSystem.infoTable.setModel(model);TableColumn column1 = StudentSystem.infoTable.getColumnModel().getColumn(0);column1.setMaxWidth(40);column1.setMinWidth(40);TableColumn column3 = StudentSystem.infoTable.getColumnModel().getColumn(2);column3.setMaxWidth(40);column3.setMinWidth(40);}}
}public static void flashInfo() {Connect dbconn = new Connect();Statement stmt = null;ResultSet rs = null;info.clear();try {stmt = dbconn.getConnection().createStatement();//创建一个 Statement 对象,封装 SQL 语句发送给数据库rs = stmt.executeQuery("select * from my_address_book");//下达命令执行查询语句并且存放在ResultSet对象中while (rs.next()) {Vector<String> row = new Vector<String>();row.add(rs.getString(1));row.add(rs.getString(2));row.add(rs.getString(3));row.add(rs.getString(4));row.add(rs.getString(5));row.add(rs.getString(6));row.add(rs.getString(7));info.add(row);}rs.close();} catch (SQLException e) {e.printStackTrace();//在命令行打印异常信息在程序中出错的位置及原因} finally {try {if (stmt != null) {stmt.close();}if (rs != null) {rs.close();}} catch (SQLException e) {e.printStackTrace();}}}
4.7 查找学生信息
查找学生信息界面,实现方法如下:
- 定义查找学生信息的相关组件;
- 通过读取用户输入信息建立数据库连接读取数据;
- 以表格形式显示查找结果
- 完成相应功能。
运行结果:
图16 以政治面貌查询学生信息
图17 以姓名关键字查询学生信息
代码:
protected void searchInfo(String key) {//搜索Connect dbconn = new Connect();Statement stmt = null;ResultSet rs = null;try {stmt = dbconn.getConnection().createStatement();String sql = "select * from my_address_book where name like'%" + key + "%'";String sql2 = "select * from my_address_book where sex like'%" + key + "%'";String sql3 = "select * from my_address_book where telephone like'%" + key + "%'";String sql4 = "select * from my_address_book where number like'%" + key + "%'";String sql5 = "select * from my_address_book where birthday like'%" + key + "%'";String sql6 = "select * from my_address_book where note like'%" + key + "%'";rs = stmt.executeQuery(sql);rs = stmt.executeQuery(sql2);rs = stmt.executeQuery(sql3);rs = stmt.executeQuery(sql4);rs = stmt.executeQuery(sql5);rs = stmt.executeQuery(sql6);info.clear();while (rs.next()) {Vector<String> row = new Vector<String>();//创建自增长数组row.add(rs.getString(1));//向Vector中添加值row.add(rs.getString(2));row.add(rs.getString(3));row.add(rs.getString(4));row.add(rs.getString(5));row.add(rs.getString(6));row.add(rs.getString(7));info.add(row);}} catch (SQLException e) {e.printStackTrace();} finally {try {if (stmt != null) {stmt.close();}if (rs != null) {rs.close();}} catch (SQLException e) {e.printStackTrace();}DefaultTableModel model = new DefaultTableModel(StudentSystem.info, StudentSystem.column);//构造一个 DefaultTableModel,并通过将 data 和 columnNames 传递到 setDataVector 方法来初始化该表。StudentSystem.infoTable.setModel(model);//数据绑定TableColumn column1 = StudentSystem.infoTable.getColumnModel().getColumn(0);column1.setMaxWidth(40);column1.setMinWidth(40);TableColumn column3 = StudentSystem.infoTable.getColumnModel().getColumn(2);column3.setMaxWidth(40);column3.setMinWidth(40);}}
源代码:
Connect.java
package com.txl;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;public class Connect {private static String driverName = "com.mysql.cj.jdbc.Driver";private static String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf8&ServerTimezone=GMT&useSSL=false&serverTimezone=UTC";private static String userName = "root";private static String password = "111111";private Connection conn;private Statement stmt;public Connect() {try {Class.forName(driverName);//加载数据库} catch (ClassNotFoundException e) {e.printStackTrace();}}public Connection getConnection() throws SQLException {return DriverManager.getConnection(url, userName, password);//使用DriverManger获取数据库连接}public void dispose() {try {if (conn != null) {conn.close();}if (stmt != null) {stmt.close();}} catch (SQLException e) {e.printStackTrace();}}
}
Login.java
package com.txl;import java.awt.FlowLayout;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPasswordField;//登录界面
public class Login {public static void main(String args[]) {Login l=new Login();//实例化Login对象l.showUI();}public void showUI() {JFrame login=new JFrame();//创建一个JFrame容器窗口login.setTitle("登录系统");//设置标题login.setSize(340,240);//设置窗口大小login.setDefaultCloseOperation(3);//0-DO_NITHING窗口无法关闭;1-HIDE隐藏程序界面但没有关闭程序;2-DISPOSE自动隐藏释放窗体,继续运行应用程序;3-EXITlogin.setLocationRelativeTo(null);//设置窗口位置相对于指定组件的位置login.setResizable(false);//设置窗口不可被调整大小,布尔值//FlowLayout fl=new FlowLayout(FlowLayout.CENTER,5,5);login.setLayout(new FlowLayout());//FloeLayout默认居中对齐,水平、垂直间距默认为5个单位login.setVisible(true);//窗体可见//用户名标签组件JLabel labname=new JLabel();labname.setText("用户名:");labname.setPreferredSize(new Dimension(60, 60));//设置最适合窗口的位置(setPreferredSize)和JLable标签组件的宽度和高度(Dimension)login.add(labname);//加入JFrame窗口JTextField textname=new JTextField();//创建一个JTextField文本框用于输入用户名textname.setPreferredSize(new Dimension(250, 30));login.add(textname);//加入到JFrame窗口中//密码标签组件JLabel labpassword=new JLabel();labpassword.setText("密 码:");labpassword.setPreferredSize(new Dimension(60, 60));login.add(labpassword);JPasswordField jp=new JPasswordField();jp.setPreferredSize(new Dimension(250, 30));login.add(jp);//登录按钮JButton button=new JButton();button.setText("登录"); button.setPreferredSize(new Dimension(100, 40));login.add(button);login.setVisible(true);//为登录键添加鼠标事件监听器button.addMouseListener(new MouseAdapter() {public void mouseClicked(MouseEvent e) {Connect dbconn = new Connect();//实例化Connect对象Statement stmt = null;ResultSet rs = null;try {//用于创建一个 Statement 对象,封装 SQL 语句发送给数据库,通常用来执行不带参数的 SQL 语句stmt = dbconn.getConnection().createStatement();//执行查询;用statement类的executeQuery()方法来下达select指令以查询数据库,把数据库响应的查询结果存放在ResultSet类对象中供我们使用//select * from查询在数据库中表内信息rs = stmt.executeQuery("select * from my_address_login where username='"+textname.getText()+"' and password='"+jp.getText()+"'");if (rs.next()) {new StudentSystem();//主界面login.dispose();//释放登录界面窗口占用的屏幕资源}else{JOptionPane.showMessageDialog(null, "用户名或密码不正确!!!","提示",2);//java弹窗JOptionPane.showMessageDialog(null, "提示内容" ,"标题", -1~3);}rs.close();} catch (SQLException e1) {e1.printStackTrace();//在命令行打印异常信息在程序中出错的位置及原因,显示出更深的调用信息//System.out.println(e1);} finally {try {if (stmt != null) {stmt.close();}if (rs != null) {rs.close();}} catch (SQLException e1) {e1.printStackTrace();}}}});}
}
StudentSystem.java
package com.txl;import java.awt.*;
import java.awt.event.*;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;public class StudentSystem extends JFrame implements ActionListener {//继承自JFrame使得这个类成为一个窗体,可以对窗体的属性进行扩展并且可以定义自己需要的特殊操作方法private static final long serialVersionUID = 1L;//把java对象序列化而后进行保存private Map<String, String> PersonInfo;public static Vector<Vector<String>> info = new Vector<Vector<String>>();private JLabel keyLab;private JButton searchBtn, createBtn, updateBtn, deleteBtn,exitBtn;public static JTable infoTable;private JTextField keyText;public static Vector<String> column;public StudentSystem() {PersonInfo = new HashMap<String, String>();//数组和链表的结合体,HashMap底层就是一个数组结构,数组中的每一项又是一个链表。新建一个HashMap的时候,就会初始化一个数组Font font = new Font("宋体", Font.PLAIN, 15);//设置字体,类型和大小;Front.PLAIN普通,Front.BLOD加粗,Front.ITALIC斜体JPanel pNorth = new JPanel();pNorth.setLayout(new FlowLayout(FlowLayout.RIGHT));keyLab = new JLabel("请输入关键字:");keyText = new JTextField(10);//搜索文本框//创建系统功能按钮searchBtn = new JButton("搜索学生信息");createBtn = new JButton("新增学生信息");updateBtn = new JButton("修改学生信息");deleteBtn = new JButton("删除学生信息");exitBtn = new JButton("退出系统");//设置字体大小keyLab.setFont(font);searchBtn.setFont(font); createBtn.setFont(font); updateBtn.setFont(font); deleteBtn.setFont(font);exitBtn.setFont(font);//添加监听器searchBtn.addActionListener(this);createBtn.addActionListener(this);updateBtn.addActionListener(this);deleteBtn.addActionListener(this);exitBtn.addActionListener(this);//在JPanel面板的上方加入搜索功能所需的一系列组件pNorth.add(keyLab);pNorth.add(keyText);pNorth.add(searchBtn);//在JPanel面板下方加入系统功能组件JPanel pSouth = new JPanel();pSouth.add(createBtn);pSouth.add(updateBtn);pSouth.add(deleteBtn);pSouth.add(exitBtn);//表格数据column = new Vector<String>();column.add("编号");column.add("姓名");column.add("性别");column.add("电话");column.add("学号");column.add("生日");column.add("政治面貌");flashInfo();//将数据存入数据库infoTable = new JTable(info, column);TableColumn column1 = infoTable.getColumnModel().getColumn(0);column1.setPreferredWidth(30);//自适应TableColumn column3 = infoTable.getColumnModel().getColumn(2);column3.setPreferredWidth(30);//自适应JScrollPane pCenter = new JScrollPane(infoTable);//创建垂直滚动面板this.add(pNorth, "North");this.add(pCenter, "Center");this.add(pSouth, "South");this.setTitle("学生信息管理系统");this.setSize(800, 450);this.setVisible(true);this.setLocationRelativeTo(null);this.setResizable(false);this.setDefaultCloseOperation(EXIT_ON_CLOSE);}public static void flashInfo() {Connect dbconn = new Connect();Statement stmt = null;ResultSet rs = null;info.clear();try {stmt = dbconn.getConnection().createStatement();//创建一个 Statement 对象,封装 SQL 语句发送给数据库rs = stmt.executeQuery("select * from my_address_book");//下达命令执行查询语句并且存放在ResultSet对象中while (rs.next()) {Vector<String> row = new Vector<String>();row.add(rs.getString(1));row.add(rs.getString(2));row.add(rs.getString(3));row.add(rs.getString(4));row.add(rs.getString(5));row.add(rs.getString(6));row.add(rs.getString(7));info.add(row);}rs.close();} catch (SQLException e) {e.printStackTrace();//在命令行打印异常信息在程序中出错的位置及原因} finally {try {if (stmt != null) {stmt.close();}if (rs != null) {rs.close();}} catch (SQLException e) {e.printStackTrace();}}}public void actionPerformed(ActionEvent e) {int rowNum = infoTable.getSelectedRow();//返回第一个选定行的索引if (rowNum != -1) {PersonInfo = new HashMap<String, String>();//将值插入HasMap中PersonInfo.put("id", (String) infoTable.getValueAt(rowNum, 0));//返回表格row和column位置的单元格值PersonInfo.put("name", (String) infoTable.getValueAt(rowNum, 1));PersonInfo.put("sex", (String) infoTable.getValueAt(rowNum, 2));PersonInfo.put("telephone", (String) infoTable.getValueAt(rowNum, 3));PersonInfo.put("number", (String) infoTable.getValueAt(rowNum, 4));PersonInfo.put("birthday", (String) infoTable.getValueAt(rowNum, 5));PersonInfo.put("note", (String) infoTable.getValueAt(rowNum, 6));}if (e.getSource() == searchBtn) {//搜索String keyStr = keyText.getText();searchInfo(keyStr);} else if (e.getSource() == createBtn) {//新建MyDialog InsertPane = new MyDialog("新建学生信息", new HashMap<String, String>());InsertPane.setVisible(true);} else if (e.getSource() == updateBtn) {//修改if (rowNum == -1) {JOptionPane.showMessageDialog(null, "请选择学生");//提示弹窗}MyDialog UpdatePane = new MyDialog("修改学生信息", PersonInfo);UpdatePane.setVisible(true);} else if (e.getSource() == deleteBtn) {//删除if (rowNum == -1) {JOptionPane.showMessageDialog(null, "请选择学生");//提示弹窗}MyDialog DeletePane = new MyDialog("删除学生信息", PersonInfo);DeletePane.setVisible(true);}else if(e.getSource()==exitBtn) {//退出this.setVisible(false);}}protected void searchInfo(String key) {//搜索Connect dbconn = new Connect();Statement stmt = null;ResultSet rs = null;try {stmt = dbconn.getConnection().createStatement();String sql = "select * from my_address_book where name like'%" + key + "%'";/*String sql2 = "select * from my_address_book where sex like'%" + key + "%'";String sql3 = "select * from my_address_book where telephone like'%" + key + "%'";*///String sql4 = "select * from my_address_book where number like'%" + key + "%'";/*String sql5 = "select * from my_address_book where birthday like'%" + key + "%'";String sql6 = "select * from my_address_book where note like'%" + key + "%'";*/rs = stmt.executeQuery(sql);/*rs = stmt.executeQuery(sql2);rs = stmt.executeQuery(sql3);*///rs = stmt.executeQuery(sql4);/*rs = stmt.executeQuery(sql5);rs = stmt.executeQuery(sql6);*/info.clear();while (rs.next()) {Vector<String> row = new Vector<String>();//创建自增长数组row.add(rs.getString(1));//向Vector中添加值row.add(rs.getString(2));row.add(rs.getString(3));row.add(rs.getString(4));row.add(rs.getString(5));row.add(rs.getString(6));row.add(rs.getString(7));info.add(row);}} catch (SQLException e) {e.printStackTrace();} finally {try {if (stmt != null) {stmt.close();}if (rs != null) {rs.close();}} catch (SQLException e) {e.printStackTrace();}DefaultTableModel model = new DefaultTableModel(StudentSystem.info, StudentSystem.column);//构造一个 DefaultTableModel,并通过将 data 和 columnNames 传递到 setDataVector 方法来初始化该表。StudentSystem.infoTable.setModel(model);//数据绑定TableColumn column1 = StudentSystem.infoTable.getColumnModel().getColumn(0);column1.setMaxWidth(40);column1.setMinWidth(40);TableColumn column3 = StudentSystem.infoTable.getColumnModel().getColumn(2);column3.setMaxWidth(40);column3.setMinWidth(40);}}public static void main(String[] args) {new StudentSystem();}
}
MyDiaolg.java
package com.txl;import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;public class MyDialog extends JDialog implements ActionListener {private static final long serialVersionUID = 1L;//把java对象序列化而后进行保存private Connect dbconn = new Connect();private static String id;private JPanel pCenter, pSouth;private JLabel nameLab, sexLab, mailLab, birthLab, phoneLab,noteLab;private JTextField nameText, mailText, birthText, phoneText,noteText;private JComboBox<String> sex;private JButton yesBtn, noBtn;public MyDialog() {}public MyDialog(String title, Map<String, String> info) {id = info.get("id");if("删除联系人".equals(title)) {deletePerson();}else {Font font = new Font("宋体", Font.BOLD, 14);String[] sexType = { "-请选择-","男", "女" };//下拉列表组件添加内容pCenter = new JPanel();pCenter.setLayout(new GridLayout(5, 1));nameLab = new JLabel("姓名:");sexLab = new JLabel("性别:");mailLab = new JLabel("学号:");birthLab = new JLabel("生日:");phoneLab = new JLabel("电话:");noteLab = new JLabel("政治面貌:");nameLab.setFont(font);sexLab.setFont(font);mailLab.setFont(font);birthLab.setFont(font);phoneLab.setFont(font);noteLab.setFont(font);nameText = new JTextField(10);mailText = new JTextField(10);birthText = new JTextField(10);phoneText = new JTextField(10);noteText = new JTextField(10);sex = new JComboBox<String>(sexType);JPanel jp1 = new JPanel();jp1.setLayout(new FlowLayout(FlowLayout.LEFT));jp1.add(nameLab);jp1.add(nameText);JPanel jp5 = new JPanel();jp5.setLayout(new FlowLayout(FlowLayout.LEFT));jp5.add(sexLab);jp5.add(sex);nameText.setText(info.get("name"));sex.setSelectedItem(info.get("sex"));JPanel jp2 = new JPanel();jp2.setLayout(new FlowLayout(FlowLayout.LEFT));jp2.add(mailLab);jp2.add(mailText);mailText.setText(info.get("number"));JPanel jp3 = new JPanel();jp3.setLayout(new FlowLayout(FlowLayout.LEFT));jp3.add(birthLab);jp3.add(birthText);birthText.setText(info.get("birthday"));JPanel jp4 = new JPanel();jp4.setLayout(new FlowLayout(FlowLayout.LEFT));jp4.add(phoneLab);jp4.add(phoneText);phoneText.setText(info.get("telephone"));JPanel jp6 = new JPanel();jp6.setLayout(new FlowLayout(FlowLayout.LEFT));jp6.add(noteLab);jp6.add(noteText);noteText.setText(info.get("note"));pCenter.add(jp1);pCenter.add(jp5);pCenter.add(jp2);pCenter.add(jp3);pCenter.add(jp4);pCenter.add(jp6);pSouth = new JPanel();yesBtn = new JButton("以数据库保存");yesBtn.addActionListener(this);noBtn = new JButton("以文件保存");noBtn.addActionListener(this);pSouth.add(yesBtn);pSouth.add(noBtn);this.add(pCenter, "Center");this.add(pSouth, "South");this.setTitle(title);this.setSize(400, 450);this.setLocationRelativeTo(null);this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);}}public void actionPerformed(ActionEvent e) {//系统功能按钮监听器if (e.getSource() == yesBtn) {if (this.getTitle().equals("新建学生信息")) {dbinsertPerson();} else if (this.getTitle().equals("修改学生信息")) {updatePerson();} else if (this.getTitle().equals("删除学生信息")) {deletePerson();}} else if (e.getSource() == noBtn) {fileinsertPerson();}}public void insertPerson() {if (nameText.getText().isEmpty()) {JOptionPane.showMessageDialog(null, "请输入姓名!");//提示弹窗return;}}public void dbinsertPerson(){//将新建的学生信息写入数据库的表中boolean flag=true;String sql = "insert into my_address_book(name, sex, telephone, number, birthday, note)value(?,?,?,?,?,?)";try {//PreparedStatement 对象已预编译过,所以其执行速度要快于 Statement 对象,多次执行的 SQL 语句经常创建为 PreparedStatement 对象,以提高效率。作为 Statement 的子类,PreparedStatement 继承了 Statement 的所有功能PreparedStatement pstmt = dbconn.getConnection().prepareStatement(sql);pstmt.setString(1, nameText.getText());pstmt.setString(2, (String) sex.getSelectedItem());pstmt.setString(3, phoneText.getText());pstmt.setString(4, mailText.getText());pstmt.setString(5, birthText.getText());pstmt.setString(6, noteText.getText());pstmt.executeUpdate();} catch (SQLException e) {e.printStackTrace();JOptionPane.showMessageDialog(null, "新建学生信息失败!");//提示弹窗flag = false;} finally {dispose();if (flag) {JOptionPane.showMessageDialog(null, "新建学生信息成功!");//提示弹窗}StudentSystem.flashInfo();//将数据写入数据库DefaultTableModel model = new DefaultTableModel(StudentSystem.info, StudentSystem.column);StudentSystem.infoTable.setModel(model);TableColumn column1 = StudentSystem.infoTable.getColumnModel().getColumn(0);column1.setMaxWidth(40);column1.setMinWidth(40);TableColumn column3 = StudentSystem.infoTable.getColumnModel().getColumn(2);column3.setMaxWidth(40);column3.setMinWidth(40);}}public void fileinsertPerson(){//将新建的学生信息写入文件中boolean flag=true;try {StringBuffer sbf=new StringBuffer();sbf.append(nameText.getText()).append(" ").append((String) sex.getSelectedItem()).append(" ").append(phoneText.getText()).append(" ").append(mailText.getText()).append(" ").append(birthText.getText()).append(" ").append(noteText.getText());File file = new File("information.txt");FileOutputStream fos = null;if(!file.exists()){file.createNewFile();//如果文件不存在,就创建该文件fos = new FileOutputStream(file);//首次写入获取}else{//如果文件已存在,就在文件末尾追加写入fos = new FileOutputStream(file,true);}OutputStreamWriter osw = new OutputStreamWriter(fos, "gbk");//指定以UTF-8格式写入文件osw.write(sbf.toString());osw.write("\r\n");osw.close();} catch (Exception e) {e.printStackTrace();JOptionPane.showMessageDialog(null, "新建学生信息失败!");//提示弹窗flag = false;} finally {dispose();if (flag) {JOptionPane.showMessageDialog(null, "新建学生信息成功!");//提示弹窗}}}public void deletePerson() {//删除信息String sql = "delete from my_address_book where id=?";try {//PreparedStatement 对象已预编译过,所以其执行速度要快于 Statement 对象,多次执行的 SQL 语句经常创建为 PreparedStatement 对象,以提高效率。作为 Statement 的子类,PreparedStatement 继承了 Statement 的所有功能PreparedStatement pstmt = dbconn.getConnection().prepareStatement(sql);pstmt.setString(1, id);pstmt.executeUpdate();} catch (SQLException e) {e.printStackTrace();} finally {dispose();StudentSystem.flashInfo();DefaultTableModel model = new DefaultTableModel(StudentSystem.info, StudentSystem.column);JOptionPane.showMessageDialog(null, "删除成功!");StudentSystem.infoTable.setModel(model);TableColumn column1 = StudentSystem.infoTable.getColumnModel().getColumn(0);column1.setMaxWidth(40);column1.setMinWidth(40);TableColumn column3 = StudentSystem.infoTable.getColumnModel().getColumn(2);column3.setMaxWidth(40);column3.setMinWidth(40);}}public void updatePerson() {//修改信息if (nameText.getText().isEmpty()) {JOptionPane.showMessageDialog(null, "请输入姓名!");//提示弹窗}String sql = "update my_address_book set name=?,sex=?,telephone=?,number=?,birthday=?,note=? where id=?";try {//PreparedStatement 对象已预编译过,所以其执行速度要快于 Statement 对象,多次执行的 SQL 语句经常创建为 PreparedStatement 对象,以提高效率。作为 Statement 的子类,PreparedStatement 继承了 Statement 的所有功能PreparedStatement pstmt = dbconn.getConnection().prepareStatement(sql);pstmt.setString(1, nameText.getText());pstmt.setString(2, (String) sex.getSelectedItem());pstmt.setString(3, phoneText.getText());pstmt.setString(4, mailText.getText());pstmt.setString(5, birthText.getText());pstmt.setString(6, noteText.getText());pstmt.setString(7, id);pstmt.executeUpdate();} catch (SQLException e) {e.printStackTrace();} finally {dispose();StudentSystem.flashInfo();DefaultTableModel model = new DefaultTableModel(StudentSystem.info, StudentSystem.column);StudentSystem.infoTable.setModel(model);TableColumn column1 = StudentSystem.infoTable.getColumnModel().getColumn(0);column1.setMaxWidth(40);column1.setMinWidth(40);TableColumn column3 = StudentSystem.infoTable.getColumnModel().getColumn(2);column3.setMaxWidth(40);column3.setMinWidth(40);}}
}
(解析+源码)基于JAVA Swing+MySQL实现学生信息管理系统(增、删、改、查)数据库/文件存储相关推荐
- 基于Java Swing+mysql的学生信息管理系统
学生信息管理系统 学生管理系统目录 学生信息管理系统 一.前期工作 ①下载eclipse.mysql.navicat ②建立navicat与mysql的连接 二.明确项目的具体实现思路 ★系统功能分析 ...
- Eclipse+Java+Swing+Mysql实现学生信息管理系统
目录 一.系统介绍 1.开发环境 2.技术选型 3.系统功能 4.数据库 二.系统展示 1.注册系统 2.登录系统 3.系统主页面 4.添加学生信息 5.修改学生信息 6.查询学生信息 三.部分代码 ...
- 基于Java+Swing+Mysql实现汽车信息管理系统
基于Java+Swing+Mysql实现汽车信息管理系统 一.系统介绍 二.功能展示 1.登陆 2.车辆信息 3.车辆入库 4.车辆出库 5.车辆查询 6.车辆信息修改 三.数据库 四.其它 1.其他 ...
- 【Java课程设计】基于Java Swing+MySQL的学生基本信息管理系统----附git仓库地址
一.项目简介 功能描述: 基于Java Swing+MySQL的学生基本信息管理系统,支持对学院.班级.学生信息的增删改查. 参考git地址或博客地址: https://www.bilibili.co ...
- 基于JAVA+SpringMVC+MYSQL的学生信息管理系统
项目功能: 々. 这个程序可以允许管理员创建新用户和删除旧用户. 々. 管理员可以查看所有用户的具体信息,例如姓名,电话,家庭住址,家长电话. 々. 如果学生外出,管理员可以对这些外出学生进行编辑.可 ...
- Eclipse+Java+Swing+Mysql实现员工信息管理系统
目录 一.系统介绍 1.开发环境 2.技术选型 3.系统功能 4.数据库 二.系统展示 1.登录系统 2.主页面 3.部门管理 4.职位管理 5.员工管理 三.部分代码 AdminDao.java D ...
- 基于Java和MySql的产业信息管理系统的设计与实现 毕业设计-附源码260839
ssm产业信息管理系统 摘 要 随着社会的发展,社会的方方面面都在利用信息化时代的优势.互联网的优势和普及使得各种系统的开发成为必需. 本文以实际运用为开发背景,运用软件工程原理和开发方法,它主要是采 ...
- ssm基于Java和MySql的产业信息管理系统的设计与实现毕业设计源码260839
ssm产业信息管理系统 摘 要 随着社会的发展,社会的方方面面都在利用信息化时代的优势.互联网的优势和普及使得各种系统的开发成为必需. 本文以实际运用为开发背景,运用软件工程原理和开发方法,它主要是采 ...
- 基于Java+Swing+mysql餐厅点餐管理系统
基于Java+Swing+mysql餐厅点餐管理系统 一.系统介绍 二.功能展示 1.用户登陆 2.用户注册(顾客) 3.顾客可以点餐 4.顾客可以查看订单信息 5.顾客可以修改个人信息 6.新增套餐 ...
最新文章
- 开发Eclipse自定义控件
- Android四大基本组件介绍与生命周期
- mysql 中修改对象_在MySQL中,创建一个数据库后,还可以对象其进行修改,不过这里的修改是指可以修改被创建数据库的相关参数,也可以修改数据库名。...
- 帕金森患者的新曙光!AI无线智能探测系统诞生
- python exception的传递
- P3899 [湖南集训]谈笑风生
- python持久层框架_SQLAlchemy
- 2022新版完整版青龙面板对接机器人,傻妞对接onebot(oicq)协议实现机器人功能
- Unity Shader·科技感描边效果(利用Robert算子边缘检测)
- 最新河南电信、网通(联通)、铁通DNS地址ip
- 手把手教你快速入门 APP 的开发
- 一张图解决为什么校外访问不了学校购买的中国知网
- 世界排名第一的免费开源WMS仓储物流管理系统介绍
- 用chrome按F12抓包 页面跳转POST一瞬间就闪没了
- 【数据结构】初识数据结构,十分钟带你玩转算法复杂度
- 2023年华为认证HCIA云计算题库(H13-511)
- 机器学习-无监督学习-聚类:聚类方法(一)--- k-Means(k-均值)算法,k-Means++算法【使用最大期望值算法(EM算法)来求解】
- 计算机辅助设计与制造考试题,计算机辅助设计与制造试题.docx
- Spring中的各种Utils(四):ClassUtils详解
- excel转pdf在线转换器