根据学校对学生信息日常管理需要,学生信息管理系统包括以下功能:
用户登录后可以对学生信息进行增、删、改、查操作,通过数据库或者文件存储用户录入的信息。
一、功能模块划分
图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 | 私有化Map集合对象 | |
public StudentSystem() | 在面板中添加组件、标签和文本框 | |
public static void flashInfo() | 将学生信息写入数据库 | |
public void actionPerformed(ActionEvent e) | 功能按钮监听 | |
protected void searchInfo(String key) | 实现查询信息 | |
public static Vector | 实例化用于存储表格数据的Vector数组 | |
public static Vector | 实例化用于存储学生信息的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 | 定义1个下拉列表组件 | |
private JButton yesBtn, noBtn | 定义2个按钮,用于给用户选择储存方式 | |
public MyDialog(String title, Map | 构造方法,用于窗口添加组件和标案等 | |
public void actionPerformed(ActionEvent e) | 系统功能按钮监听器模块 | |
public void insertPerson() | 添加信息当用户输入无效信息时提示模块 | |
public void dbinsertPerson() | 将新建的学生信息写入数据库的表中模块 | |
public void fileinsertPerson() | 将新建的学生信息写入文件中模块 | |
public void deletePerson() | 删除指定学生信息模块 | |
public void updatePerson() | 修改指定学生信息模块 |
四、各个模块实现方法
4.1 连接数据库
与创建的数据库进行连接,实现步骤如下:
代码:
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-EXIT login.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();//数组和链表的结合体,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 (); 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 row = new Vector (); 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()) { Vectorrow = new Vector (); 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()) { Vectorrow = new Vector ();//创建自增长数组 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-EXIT login.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 MapPersonInfo; public static Vector > info = new Vector >(); private JLabel keyLab; private JButton searchBtn, createBtn, updateBtn, deleteBtn,exitBtn; public static JTable infoTable; private JTextField keyText; public static Vector column; public StudentSystem() { PersonInfo = new HashMap ();//数组和链表的结合体,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 (); 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 row = new Vector (); 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 (); //将值插入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 ()); 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 row = new Vector ();//创建自增长数组 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 JComboBoxsex; private JButton yesBtn, noBtn; public MyDialog() {} public MyDialog(String title, Map 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 (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); } } }
上一篇:pgsql 时区查看和修改