很多剛入門的同學,不清楚如何用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; } }
以上就是全部的程式碼了,大家可以參考一下,或者直接建立一個專案,然後程式碼複製進去,基本都可以跑起來。