很多剛入門的同學,不清楚如何用java、swing去開發出一個系統?
不清楚如何使用java代碼去操作數據庫進行增刪改查一些列操作,不清楚java代碼和數據庫(mysql、sqlserver)之間怎么聯系起來。
一個系統本質上就是一系列的模塊組合起來的,只要懂了一個模塊的實現,其他的自然而然的也就不難。
今天,我們通過做一個學生管理的一個通俗模塊,去給大家演示如何用java+swing+mysql去實現一個學生管理的曾刪改查。
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代碼了,首先設計界面,粗略思考一下,包含三個界面:學生列表查詢界面,學生信息添加界面,學生信息修改界面,其中添加界面和修改界面差不多的,界面如下:
查詢界面:
查詢界面設計代碼:
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); } } }
添加界面:
添加界面代碼:
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); } }
修改界面:
修改界面代碼:
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; } }
以上就是全部的代碼了,大家可以參考一下,或者直接創建一個項目,然后代碼復制進去,基本都可以跑起來。