swing可编辑(手把手教你用swing写一个学生的增删改查模块)

swing可编辑(手把手教你用swing写一个学生的增删改查模块)(1)

很多刚入门的同学,不清楚如何用java、swing去开发出一个系统?

不清楚如何使用java代码去操作数据库进行增删改查一些列操作,不清楚java代码和数据库(mysql、sqlserver)之间怎么联系起来。

一个系统本质上就是一系列的模块组合起来的,只要懂了一个模块的实现,其他的自然而然的也就不难。

今天,我们通过做一个学生管理的一个通俗模块,去给大家演示如何用java swing mysql去实现一个学生管理的曾删改查。

swing可编辑(手把手教你用swing写一个学生的增删改查模块)(2)

1.前期准备工作,开发工具安装,主要包括如下开发工具:

  • jdk,java开发和运行环境,1.7或者1.8的版本都可以。
  • eclispe,java代码编写工具,主要用来写java代码,当然你可以用idea
  • mysql,数据库,主要用来存储数据,5.6以上版本,8.0的版本需要注意驱动的升级
  • navicat for mysql 数据库可视化工具,主要用来操作mysql,简化数据库操作。

2.以上环境准备好之后,接下来可以进行数据库表的设计,我们可以用navicat for mysql创建一个数据库(如何创建,可以自行科普),名字叫做db_demo;

然后再新建一个数据库表t_student,sql语句如下,可自行拷贝然后执行:

DROP TABLE IF EXISTS `t_student`; CREATE TABLE `t_student` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '学生ID', `stuno` varchar(32) DEFAULT NULL COMMENT '学号', `name` varchar(32) DEFAULT NULL COMMENT '姓名', `grade` varchar(32) DEFAULT NULL COMMENT '班级', `create_time` datetime DEFAULT NULL COMMENT '添加时间', `update_time` datetime DEFAULT NULL COMMENT '修改时间', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

这样数据库表,就已经创建好了。数据库表一般对应一个entity实体类,字段互相对应,实体类代码如下:

package com.xiaoniucr.entity; import java.util.Date; /** * 学生实体类 * @author Lenovo * */ public class Student { /** * 学生ID */ private Integer id; /** * 学号 */ private String stuno; /** * 姓名 */ private String name; /** * 班级 */ private String grade; /** * 添加时间 */ private Date creatTime; /** * 修改时间 */ private Date updateTime; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getStuno() { return stuno; } public void setStuno(String stuno) { this.stuno = stuno; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGrade() { return grade; } public void setGrade(String grade) { this.grade = grade; } public Date getCreatTime() { return creatTime; } public void setCreatTime(Date creatTime) { this.creatTime = creatTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }

3.接下来我们开始写java代码了,首先设计界面,粗略思考一下,包含三个界面:学生列表查询界面,学生信息添加界面,学生信息修改界面,其中添加界面和修改界面差不多的,界面如下:

查询界面:

swing可编辑(手把手教你用swing写一个学生的增删改查模块)(3)

查询界面设计代码:

package com.xiaoniucr.view; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.SimpleDateFormat; import java.util.List; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.border.EmptyBorder; import javax.swing.table.DefaultTableModel; import com.xiaoniucr.dao.StudentDao; import com.xiaoniucr.entity.Student; public class UserListView extends JFrame { private JPanel contentPane; private JTable table; private JTextField nameText; private StudentDao studentDao = new StudentDao(); /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { UserListView frame = new UserListView(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public UserListView() { setTitle("学生列表"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 600, 337); setLocationRelativeTo(null); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JscrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(10, 39, 564, 232); contentPane.add(scrollPane); Object[] columns = { "ID", "学号", "姓名", "年级", "添加时间" };// 字段 Object[][] data = null;// 需要展示的数据,一般是二维数组 DefaultTableModel model = new DefaultTableModel(data, columns); table = new JTable(model); //加载学生数据 load(null); scrollPane.setViewportView(table); JLabel lblNewLabel = new JLabel("姓名"); lblNewLabel.setBounds(10, 10, 42, 15); contentPane.add(lblNewLabel); nameText = new JTextField(); nameText.setBounds(44, 8, 115, 21); contentPane.add(nameText); nameText.setColumns(10); //查询按钮 JButton searchBtn = new JButton("查询"); searchBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { load(nameText.getText()); } }); searchBtn.setBounds(169, 8, 63, 23); contentPane.add(searchBtn); //添加按钮 JButton addBtn = new JButton("添加"); addBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { AddView view = new AddView(); view.setVisible(true); } }); addBtn.setBounds(365, 8, 63, 23); contentPane.add(addBtn); //修改按钮 JButton updateBtn = new JButton("修改"); updateBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // 获取选中行 int row = table.getSelectedRow(); if (row < 0) { JOptionPane.showMessageDialog(contentPane, "请选择一条记录", "系统提示", JOptionPane.WARNING_MESSAGE); return; } int id = Integer.valueOf(table.getValueAt(row, 0).toString()); UpdateView view = new UpdateView(id); view.setVisible(true); } }); updateBtn.setBounds(438, 8, 63, 23); //删除按钮 JButton deleteBtn = new JButton("删除"); deleteBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // 获取选中行 int row = table.getSelectedRow(); if (row < 0) { JOptionPane.showMessageDialog(contentPane, "请选择一条记录", "系统提示", JOptionPane.WARNING_MESSAGE); return; } int result = JOptionPane.showConfirmDialog(contentPane, "确认删除该学生吗?", "提示", JOptionPane.YES_NO_OPTION); if (result == 0) { int id = Integer.valueOf(table.getValueAt(row, 0).toString()); boolean flag = studentDao.delete(id); if(flag){ JOptionPane.showMessageDialog(contentPane, "删除成功!"); load(null); }else{ JOptionPane.showMessageDialog(contentPane, "操作失败", "系统提示", JOptionPane.WARNING_MESSAGE); } } return; } }); deleteBtn.setBounds(511, 8, 63, 23); contentPane.add(deleteBtn); contentPane.add(updateBtn); } // 填充表格数据 public void load(String name){ List<Student> list = studentDao.queryList(name); DefaultTableModel tableModel = (DefaultTableModel) table.getModel(); tableModel.setRowCount(0);// 清除原有行 // 填充数据 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (Student item : list) { String[] arr = new String[5]; arr[0] = item.getId() ""; arr[1] = item.getStuno(); arr[2] = item.getName(); arr[3] = item.getGrade(); arr[4] = sdf.format(item.getCreatTime()); // 添加数据到表格 tableModel.addRow(arr); } } }

添加界面:

swing可编辑(手把手教你用swing写一个学生的增删改查模块)(4)

添加界面代码:

package com.xiaoniucr.view; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.border.EmptyBorder; import com.xiaoniucr.dao.StudentDao; import com.xiaoniucr.entity.Student; public class AddView extends JFrame { private JPanel contentPane; private JTextField stunoText; private JTextField nameText; private JTextField gradeText; private StudentDao studentDao = new StudentDao(); /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { AddView frame = new AddView(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public AddView() { setTitle("学生添加"); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100, 100, 443, 300); setLocationRelativeTo(null); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JLabel lblNewLabel = new JLabel("学号:"); lblNewLabel.setBounds(112, 50, 43, 15); contentPane.add(lblNewLabel); stunoText = new JTextField(); stunoText.setBounds(151, 47, 160, 21); contentPane.add(stunoText); stunoText.setColumns(10); JLabel lblNewLabel_1 = new JLabel("姓名:"); lblNewLabel_1.setBounds(112, 93, 43, 15); contentPane.add(lblNewLabel_1); nameText = new JTextField(); nameText.setBounds(151, 90, 160, 21); contentPane.add(nameText); nameText.setColumns(10); JLabel lblNewLabel_2 = new JLabel("班级:"); lblNewLabel_2.setBounds(111, 134, 43, 15); contentPane.add(lblNewLabel_2); gradeText = new JTextField(); gradeText.setBounds(151, 131, 160, 21); contentPane.add(gradeText); gradeText.setColumns(10); //保存 JButton saveBtn = new JButton("保存"); saveBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String stuno = stunoText.getText(); String name = nameText.getText(); String grade = gradeText.getText(); if(stuno == null || "".equals(stuno)){ JOptionPane.showMessageDialog(contentPane, "请输入学号", "系统提示", JOptionPane.WARNING_MESSAGE); return; } if(name == null || "".equals(name)){ JOptionPane.showMessageDialog(contentPane, "请输入姓名", "系统提示", JOptionPane.WARNING_MESSAGE); return; } if(grade == null || "".equals(grade)){ JOptionPane.showMessageDialog(contentPane, "请输入班级", "系统提示", JOptionPane.WARNING_MESSAGE); return; } Student student = new Student(); student.setStuno(stuno); student.setName(name); student.setGrade(grade); boolean flag = studentDao.save(student); if(flag){ dispose(); JOptionPane.showMessageDialog(contentPane, "添加成功,刷新可查看!"); }else{ JOptionPane.showMessageDialog(contentPane, "操作失败", "系统提示", JOptionPane.WARNING_MESSAGE); } return; } }); saveBtn.setBounds(151, 180, 74, 23); contentPane.add(saveBtn); //取消 JButton cancleBtn = new JButton("取消"); cancleBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); cancleBtn.setBounds(237, 180, 74, 23); contentPane.add(cancleBtn); } }

修改界面:

swing可编辑(手把手教你用swing写一个学生的增删改查模块)(5)

修改界面代码:

package com.xiaoniucr.view; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.border.EmptyBorder; import com.xiaoniucr.dao.StudentDao; import com.xiaoniucr.entity.Student; public class UpdateView extends JFrame { private JPanel contentPane; private JTextField stunoText; private JTextField nameText; private JTextField gradeText; private StudentDao studentDao = new StudentDao(); /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { UpdateView frame = new UpdateView(1); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public UpdateView(final int id) { setTitle("学生编辑"); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100, 100, 443, 300); setLocationRelativeTo(null); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JLabel lblNewLabel = new JLabel("学号:"); lblNewLabel.setBounds(112, 50, 43, 15); contentPane.add(lblNewLabel); stunoText = new JTextField(); stunoText.setBounds(151, 47, 160, 21); contentPane.add(stunoText); stunoText.setColumns(10); JLabel lblNewLabel_1 = new JLabel("姓名:"); lblNewLabel_1.setBounds(112, 93, 43, 15); contentPane.add(lblNewLabel_1); nameText = new JTextField(); nameText.setBounds(151, 90, 160, 21); contentPane.add(nameText); nameText.setColumns(10); JLabel lblNewLabel_2 = new JLabel("班级:"); lblNewLabel_2.setBounds(111, 134, 43, 15); contentPane.add(lblNewLabel_2); gradeText = new JTextField(); gradeText.setBounds(151, 131, 160, 21); contentPane.add(gradeText); gradeText.setColumns(10); //保存 JButton saveBtn = new JButton("保存"); saveBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String stuno = stunoText.getText(); String name = nameText.getText(); String grade = gradeText.getText(); if(stuno == null || "".equals(stuno)){ JOptionPane.showMessageDialog(contentPane, "请输入学号", "系统提示", JOptionPane.WARNING_MESSAGE); return; } if(name == null || "".equals(name)){ JOptionPane.showMessageDialog(contentPane, "请输入姓名", "系统提示", JOptionPane.WARNING_MESSAGE); return; } if(grade == null || "".equals(grade)){ JOptionPane.showMessageDialog(contentPane, "请输入班级", "系统提示", JOptionPane.WARNING_MESSAGE); return; } Student student = new Student(); student.setId(id); student.setStuno(stuno); student.setName(name); student.setGrade(grade); boolean flag = studentDao.update(student); if(flag){ dispose(); JOptionPane.showMessageDialog(contentPane, "修改成功,刷新可查看!"); }else{ JOptionPane.showMessageDialog(contentPane, "操作失败", "系统提示", JOptionPane.WARNING_MESSAGE); } return; } }); saveBtn.setBounds(151, 180, 74, 23); contentPane.add(saveBtn); //取消 JButton cancleBtn = new JButton("取消"); cancleBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); cancleBtn.setBounds(237, 180, 74, 23); contentPane.add(cancleBtn); //数据回显 Student student = studentDao.getById(id); stunoText.setText(student.getStuno()); nameText.setText(student.getName()); gradeText.setText(student.getGrade()); } }

4.界面设计完成之后,就是连接数据库了,连接数据库需要依赖一个jar包:mysql-connector-java-5.1.21.jar,数据库连接代码如下:包含数据库的连接和使用完成之后的一些资源释放。

package com.xiaoniucr.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class JDBCUtils { //数据库连接地址 public static String URL = "jdbc:mysql://localhost:3306/db_demo?useUnicode=true&characterEncoding=utf8"; //数据库驱动 public static String DRIVER = "com.mysql.jdbc.Driver"; //数据库用户名 public static String USER = "root"; //数据库密码 public static String PWD = "123456"; /* * 数据库连接 */ public static Connection getConnection() { Connection con = null; try { // 加载驱动 Class.forName(DRIVER); // 获取连接对象 con = DriverManager.getConnection(URL, USER, PWD); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return con; } /** * 关闭连接资源 * @param con 连接对象 * @param pstmt 预编译对象 * @param rs 结果集 */ public static void close(Connection con, PreparedStatement pstmt, ResultSet rs) { try { if (rs != null){ rs.close(); } if (pstmt != null){ pstmt.close(); } if (con != null){ con.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

5.数据库连接完成之后,就是数据库的操作了,这里包含三个操作,学生列表的查询,学生信息的添加保存到数据库,和学生信息的修改保存,数据库操作代码如下:

package com.xiaoniucr.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.xiaoniucr.entity.Student; import com.xiaoniucr.util.JDBCUtils; /** * 学生数据库操作 * @author Lenovo * */ public class StudentDao { /** * 查询学生列表 * @param name 学生姓名 * @return */ public List<Student> queryList(String name){ List<Student> list = new ArrayList<Student>(); Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JDBCUtils.getConnection(); List<Object> params = new ArrayList<>(); StringBuffer sb = new StringBuffer("select * from t_student where 1=1 "); if(name != null && !"".equals(name)){ sb.append("and name like ? "); params.add(name); } sb.append("order by create_time desc"); pstmt = con.prepareStatement(sb.toString()); if(params != null && params.size()>0){ for(int i=0; i<params.size(); i ){ pstmt.setObject(i, params.get(i)); } } rs = pstmt.executeQuery(); while(rs.next()){ Student student = new Student(); student.setId(rs.getInt("id")); student.setStuno(rs.getString("stuno")); student.setName(rs.getString("name")); student.setGrade(rs.getString("grade")); student.setCreatTime(rs.getDate("create_time")); student.setUpdateTime(rs.getDate("update_time")); list.add(student); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { JDBCUtils.close(con, pstmt, rs); } return list; } /** * 保存学生信息 * @param student * @return */ public boolean save(Student student){ Connection con = null; String sql = "insert into t_student(stuno,name,grade,create_time,update_time) values(?,?,?,?,?)"; PreparedStatement pstmt = null; try { con = JDBCUtils.getConnection(); pstmt = con.prepareStatement(sql); pstmt.setString(1, student.getStuno()); pstmt.setString(2, student.getName()); pstmt.setString(3, student.getGrade()); Date date = new Date(); pstmt.setTimestamp(4, new Timestamp(date.getTime())); pstmt.setTimestamp(5, new Timestamp(date.getTime())); int rows = pstmt.executeUpdate(); if(rows > 0){ return true; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { JDBCUtils.close(con, pstmt, null); } return false; } /** * 修改学生信息 * @param student * @return */ public boolean update(Student student){ Connection con = null; String sql = "update t_student set stuno=?,name=?,grade=?,update_time=? where id=?"; PreparedStatement pstmt = null; try { con = JDBCUtils.getConnection(); pstmt = con.prepareStatement(sql); pstmt.setString(1, student.getStuno()); pstmt.setString(2, student.getName()); pstmt.setString(3, student.getGrade()); Date date = new Date(); pstmt.setTimestamp(4, new Timestamp(date.getTime())); pstmt.setInt(5, student.getId()); int rows = pstmt.executeUpdate(); if(rows > 0){ return true; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { JDBCUtils.close(con, pstmt, null); } return false; } /** * 删除学生信息 * @param student * @return */ public boolean delete(int id){ Connection con = null; String sql = "delete from t_student where id=?"; PreparedStatement pstmt = null; try { con = JDBCUtils.getConnection(); pstmt = con.prepareStatement(sql); pstmt.setInt(1, id); int rows = pstmt.executeUpdate(); if(rows > 0){ return true; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { JDBCUtils.close(con, pstmt, null); } return false; } /** * 根据ID查询学生 * @param id 学生ID * @return */ public Student getById(int id){ Student student = null; Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JDBCUtils.getConnection(); String sql = "select * from t_student where id = ?"; pstmt = con.prepareStatement(sql); pstmt.setObject(1, id); rs = pstmt.executeQuery(); while(rs.next()){ student = new Student(); student.setId(rs.getInt("id")); student.setStuno(rs.getString("stuno")); student.setName(rs.getString("name")); student.setGrade(rs.getString("grade")); student.setCreatTime(rs.getDate("create_time")); student.setUpdateTime(rs.getDate("update_time")); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { JDBCUtils.close(con, pstmt, rs); } return student; } }

  以上就是全部的代码了,大家可以参考一下,或者直接创建一个项目,然后代码复制进去,基本都可以跑起来。

,

免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com

    分享
    投诉
    首页