- 博主简介:努力学习的22级计算机科学与技术本科生一枚🌸
- 博主主页: @是瑶瑶子啦
- 每日一言🌼: 勇敢的人,不是不落泪的人,而是愿意含着泪继续奔跑的人。
——《朗读者》
本篇博客的核心是基于Mysql数据库,使用JDBC对数据库(这里以简单的学生表为例)进行增删改查,且用Java自带的Swing图像包,实现简单的可视化窗口界面。
这里先对JDBC进行一个简单的介绍:
怎么来的?
学过Mysql或SqlSever等数据库的同学,应该知道,我没直接通过这两个数据库管理软件实现对数据的增删改查,是用命令行巧Sql语句进行的。但是实际开发中,绝大部分还是用代码实现对数据库的操作(代码背后的本质还是Sql语句,其实所谓代码,还不如说是用代码取调用API)。那么作为一个成熟的数据库,会提供相应的API,供程序员去调用,从而实现用代码对数据库进行操作。
原理?
但是,每个数据库的API都是由自家数据库公司的人员进行设计,差别较大,你要想直接去调用,那你还得去根据你所需要用到的数据库进行对应API的学习,学习成本很大!有没有办法,只用学一套API,实现对所有数据库的操作!于是这个时候咱们的Java靠着强大的影响力站出来了,它提出了一个框架——JDBC。
其中,数据库驱动包,主要还是由各自数据库厂商设计,作用是将原生API转换成JDBC可以调用的API(谁叫Java影响力大呢,你没有驱动包,人家就不带你玩)
再次封装?
但是当你去用JDBC后,你会发现,虽然它确实统一了数据库的API,但是一套流程下来,还是有点繁琐。于是一些大佬对JDBC进行了再次封装,得到了更好更方便的数据库操纵框架(ORM),如:MyBatis
关于如何用JDBC连接数据库,以及JDBC增删改查的基础操作知识,小黄学长已经写的很好很全面了,这里附上小黄大佬的博客连接,零基础的同学可以先去学习,此篇博客还是着重于项目方面,以项目巩固咱们的知识。
这里是我用Navicat创建好的学生表
这是Idea中项目的结构:
DatabaseManager.java:用于处理数据库操作:数据库连接、对会话窗口文件封装的增删改查的方法接口
MainFrame.java:主窗口界面,主要是四个按键:增删改查,并且定义四个案件的触发事件:创建对应处理操作的会话窗口
增删改查的会话窗口:主要就是对对话窗口的界面设置、获取对应label的对应的值、调用DatabaseManager文件中封装好的增删改查接口,进行增删改查。
import java.sql.*;
public class DatabaseManager {
private static final String DATABASE_URL = "jdbc:mysql://localhost/test";
private static final String USERNAME = "root";
private static final String PASSWORD = "55667788";
private Connection connection;
/*
构造方法,初始化数据库,创建数据库连接
*/
public DatabaseManager() {
initializeDatabase();
}
private void initializeDatabase() {
try {
connection = DriverManager.getConnection(DATABASE_URL, USERNAME, PASSWORD);
} catch (SQLException e) {
e.printStackTrace();
}
}
public boolean addStudent(String id, String name) {
try {
String query = "INSERT INTO Student (id, name) VALUES (?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, id);
preparedStatement.setString(2, name);
int rowsAffected = preparedStatement.executeUpdate();
return rowsAffected > 0;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
public boolean deleteStudent(String id) {
try {
String query = "DELETE FROM Student WHERE id = ?";
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, id);
int rowsAffected = preparedStatement.executeUpdate();
return rowsAffected > 0;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
public boolean updateStudent(String id, String name) {
try {
String query = "UPDATE Student SET name = ? WHERE id = ?";
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, name);
preparedStatement.setString(2, id);
int rowsAffected = preparedStatement.executeUpdate();
return rowsAffected > 0;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
public ResultSet retrieveStudents() {
try {
String query = "SELECT * FROM Student";
PreparedStatement preparedStatement = connection.prepareStatement(query);
return preparedStatement.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MainFrame extends JFrame {
// 以下是CRUD需要用到的4个案件
private JButton addButton;
private JButton deleteButton;
private JButton updateButton;
private JButton retrieveButton;
public MainFrame() {
setTitle("Student Management System");// 设置窗口标题为"Student Management System"
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 设置默认的关闭操作为退出应用程序
setPreferredSize(new Dimension(400, 300)); // 设置窗口的首选大小为400x300像素
JPanel mainPanel = new JPanel(new GridLayout(4, 1, 10, 10));// 创建一个面板,并使用GridLayout布局管理器,4行1列,行间距和列间距为10像素
mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));// 将面板添加到窗口的中间位置
getContentPane().add(mainPanel, BorderLayout.CENTER);
addButton = new JButton("Add Student");
deleteButton = new JButton("Delete Student");
updateButton = new JButton("Update Student");
retrieveButton = new JButton("Retrieve Students");
mainPanel.add(addButton);
mainPanel.add(deleteButton);
mainPanel.add(updateButton);
mainPanel.add(retrieveButton);
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AddStudentDialog dialog = new AddStudentDialog(MainFrame.this);// 创建"Add Student"对话框
dialog.setVisible(true);
}
});
deleteButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DeleteStudentDialog dialog = new DeleteStudentDialog(MainFrame.this); // 显示对话框
dialog.setVisible(true);
}
});
updateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
UpdateStudentDialog dialog = new UpdateStudentDialog(MainFrame.this);// 创建"Update Student"对话框
dialog.setVisible(true);
}
});
retrieveButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
RetrieveStudentsDialog dialog = new RetrieveStudentsDialog(MainFrame.this); // 创建"Retrieve Students"对话框
dialog.setVisible(true);
}
});
pack();// 调整窗口的大小,以适应组件的大小
setLocationRelativeTo(null); // 将窗口置于屏幕中央
}
/*
main()方法是程序的入口点,通过SwingUtilities.invokeLater()在事件分派线程(Event Dispatch Thread)中创建并显示MainFrame窗口。
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MainFrame frame = new MainFrame();
frame.setVisible(true);
}
});
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/*
定义了一个名为AddStudentDialog的类,该类继承自JDialog,用于创建一个添加学生对话框。
*/
public class AddStudentDialog extends JDialog {
// JTextField类型的实例变量idField和nameField分别用于输入学生的ID和姓名。
private JTextField idField;
private JTextField nameField;
// JButton类型的实例变量addButton代表添加按钮。
private JButton addButton;
private DatabaseManager databaseManager;
public AddStudentDialog(Frame owner) {
super(owner, "Add Student", true);
databaseManager = new DatabaseManager();
// 创建一个JPanel实例contentPane,作为对话框的内容面板
JPanel contentPane = new JPanel();
setContentPane(contentPane);
// 创建两个JLabel实例idLabel和nameLabel,分别用于显示"ID:"和"Name:"标签。
JLabel idLabel = new JLabel("ID:");
idField = new JTextField(10);
JLabel nameLabel = new JLabel("Name:");
nameField = new JTextField(10);
// 创建一个JButton实例addButton,用于执行添加学生操作。同时,为按钮添加一个动作监听器,当点击按钮时,会执行监听器中的代码。
addButton = new JButton("Add");
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String id = idField.getText();
String name = nameField.getText();
boolean success = databaseManager.addStudent(id, name);
if (success) {
JOptionPane.showMessageDialog(AddStudentDialog.this, "Student added successfully.");
dispose();
} else {
JOptionPane.showMessageDialog(AddStudentDialog.this, "Failed to add student.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
contentPane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
contentPane.add(idLabel, c);
c.gridx = 1;
contentPane.add(idField, c);
c.gridy = 1;
contentPane.add(nameLabel, c);
c.gridx = 1;
contentPane.add(nameField, c);
c.gridy = 2;
contentPane.add(addButton, c);
pack();
setLocationRelativeTo(owner);
}
}
import java.sql.*;
public class DatabaseManager {
private static final String DATABASE_URL = "jdbc:mysql://localhost/test";
private static final String USERNAME = "root";
private static final String PASSWORD = "55667788";
private Connection connection;
/*
构造方法,初始化数据库,创建数据库连接
*/
public DatabaseManager() {
initializeDatabase();
}
private void initializeDatabase() {
try {
connection = DriverManager.getConnection(DATABASE_URL, USERNAME, PASSWORD);
} catch (SQLException e) {
e.printStackTrace();
}
}
public boolean addStudent(String id, String name) {
try {
String query = "INSERT INTO Student (id, name) VALUES (?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, id);
preparedStatement.setString(2, name);
int rowsAffected = preparedStatement.executeUpdate();
return rowsAffected > 0;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
public boolean deleteStudent(String id) {
try {
String query = "DELETE FROM Student WHERE id = ?";
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, id);
int rowsAffected = preparedStatement.executeUpdate();
return rowsAffected > 0;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
public boolean updateStudent(String id, String name) {
try {
String query = "UPDATE Student SET name = ? WHERE id = ?";
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, name);
preparedStatement.setString(2, id);
int rowsAffected = preparedStatement.executeUpdate();
return rowsAffected > 0;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
public ResultSet retrieveStudents() {
try {
String query = "SELECT * FROM Student";
PreparedStatement preparedStatement = connection.prepareStatement(query);
return preparedStatement.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class UpdateStudentDialog extends JDialog {
private JTextField idField;
private JTextField nameField;
private JButton updateButton;
private DatabaseManager databaseManager;
public UpdateStudentDialog(Frame owner) {
super(owner, "Update Student", true);
databaseManager = new DatabaseManager();
JPanel contentPane = new JPanel();
setContentPane(contentPane);
JLabel idLabel = new JLabel("ID:");
idField = new JTextField(10);
JLabel nameLabel = new JLabel("Name:");
nameField = new JTextField(10);
updateButton = new JButton("Update");
updateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String id = idField.getText();
String name = nameField.getText();
boolean success = databaseManager.updateStudent(id, name);
if (success) {
JOptionPane.showMessageDialog(UpdateStudentDialog.this, "Student updated successfully.");
dispose();
} else {
JOptionPane.showMessageDialog(UpdateStudentDialog.this, "Failed to update student.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
contentPane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
contentPane.add(idLabel, c);
c.gridx = 1;
contentPane.add(idField, c);
c.gridy = 1;
contentPane.add(nameLabel, c);
c.gridx = 1;
contentPane.add(nameField, c);
c.gridy = 2;
contentPane.add(updateButton, c);
pack();
setLocationRelativeTo(owner);
}
}
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;
public class RetrieveStudentsDialog extends JDialog {
private JTable studentTable; // studentTable是一个私有成员变量,用于显示学生信息的表格
private DatabaseManager databaseManager; // databaseManager是一个DatabaseManager对象,用于与数据库进行交互。
public RetrieveStudentsDialog(Frame owner) {
// 调用父类的构造函数来设置对话框的标题和模态(true表示模态对话框)
super(owner, "Retrieve Students", true);
databaseManager = new DatabaseManager();
// 创建一个面板contentPane,使用边界布局管理器,并将其设置为对话框的内容面板
JPanel contentPane = new JPanel(new BorderLayout());
setContentPane(contentPane);
// 创建一个表格studentTable和一个带滚动条的面板scrollPane,用于显示学生信息的表格
studentTable = new JTable();
JScrollPane scrollPane = new JScrollPane(studentTable);
// 将scrollPane添加到contentPane的中心位置。
contentPane.add(scrollPane, BorderLayout.CENTER);
// 调用retrieveStudents()方法来检索学生信息并将其显示在表格中
retrieveStudents();
pack();
// setLocationRelativeTo(owner)将对话框定位在拥有者的中心位置。
setLocationRelativeTo(owner);
}
/*
retrieveStudents()方法用于从数据库中检索学生信息,并将其填充到表格中。
*/
private void retrieveStudents() {
// 调用databaseManager.retrieveStudents()方法从数据库中获取学生信息的ResultSet对象
ResultSet resultSet = databaseManager.retrieveStudents();
//在每次循环中,从resultSet中获取学生的ID和姓名,创建一个Vector<Object>对象表示一行数据,并将其添加到data向量中。
if (resultSet != null) {
try {
Vector<String> columnNames = new Vector<>();
columnNames.add("ID");
columnNames.add("Name");
Vector<Vector<Object>> data = new Vector<>();
while (resultSet.next()) {
Vector<Object> row = new Vector<>();
row.add(resultSet.getString("id"));
row.add(resultSet.getString("name"));
data.add(row);
}
// 创建一个DefaultTableModel对象,使用data向量作为数据,columnNames向量作为列名,并将其设置为表格的模型。
DefaultTableModel model = new DefaultTableModel(data, columnNames);
studentTable.setModel(model);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
运行MainFrame
文件即可启动程序:
点击相应按键即可实现增删改查
增:
删:
改
查: