2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > (解析+源码)基于JAVA Swing+MySQL实现学生信息管理系统(增 删 改 查)数据库/文件存储

(解析+源码)基于JAVA Swing+MySQL实现学生信息管理系统(增 删 改 查)数据库/文件存储

时间:2019-03-20 03:57:50

相关推荐

(解析+源码)基于JAVA Swing+MySQL实现学生信息管理系统(增 删 改 查)数据库/文件存储

根据学校对学生信息日常管理需要,学生信息管理系统包括以下功能:

登录系统;新建学生信息:添加学生信息;删除学生信息:对指定学生信息进行删除;修改学生信息:对指定学生信息进行修改查找学生信息:输入名字关键字、学号、政治面貌等查询符合条件的学生;退出系统。

用户登录后可以对学生信息进行增、删、改、查操作,通过数据库或者文件存储用户录入的信息。

一、功能模块划分

图1 功能模块划分图

二、数据库结构描述

2.1 数据库E-R模型

图2 登录E-R图

图3 学生E-R图

2.2 数据库关系模型--二维表

表1 登录用户名和密码

图4 录入信息后的用户名和密码

表2 学生信息表

图5 录入信息后的学生信息表

三、系统详细设计

3.1系统执行流程

图6 系统执行流程图

3.2类的划分

表3

表4

表5

表6

四、各个模块实现方法

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);}}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。