程序整体框架 :
一.数据库表格建立:
(本项目使用到了数据库的可视化软件DataGrip,需要同学们自行下载并配置环境)
首先我们需要在DataGrip中建立一个student的框架
然后建立一个studenttable表
建立列用来存储学生信息
整体框架
数据格式的编写
二.代码部分
main类:
public class Main {
public static void main(String[] args){
JDBC win=new JDBC();
//调用窗口类,创建窗口
Windows1 system=new Windows1();
system.setVisible(true);
}
}
Window1类
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
public class Windows1 extends JFrame implements ActionListener {
JLabel label1,label2,label3,label4,label5,label6;
JTextField field1,field2,field3,field4,field5,field6;
JButton button1,button2,button3,button4;
JPanel panel1,panel2,panel3;
JTable table;
DefaultTableModel model;
public Windows1(){
//设置窗口属性
setTitle("学生信息管理系统");
setSize(800,650);
//窗口居中
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//设置组件
label1=new JLabel("学号");
label2=new JLabel("姓名");
label3=new JLabel("性别");
label4=new JLabel("年龄");
label5=new JLabel("专业");
label6=new JLabel("班级");
field1=new JTextField(10);
field2=new JTextField(10);
field3=new JTextField(10);
field4=new JTextField(10);
field5=new JTextField(10);
field6=new JTextField(10);
button1=new JButton("添加");
button2=new JButton("删除");
button3=new JButton("查找");
button4=new JButton("修改");
//设置表格
String[] str={"学号","姓名","性别","年龄","专业","班级"};
model=new DefaultTableModel(str,0);
table=new JTable(model);
JScrollPane scrollPane=new JScrollPane(table);
//设置布局
panel1=new JPanel();
panel2=new JPanel();
panel3=new JPanel();
panel1.setLayout(new GridLayout(6,2));
panel1.add(label1);
panel1.add(field1);
panel1.add(label2);
panel1.add(field2);
panel1.add(label3);
panel1.add(field3);
panel1.add(label4);
panel1.add(field4);
panel1.add(label5);
panel1.add(field5);
panel1.add(label6);
panel1.add(field6);
panel2.setLayout(new FlowLayout());
panel2.add(button1);
panel2.add(button2);
panel2.add(button3);
panel2.add(button4);
panel3.setLayout(new BorderLayout());
panel3.add(panel1,BorderLayout.CENTER);
panel3.add(panel2,BorderLayout.NORTH);
panel3.add(scrollPane,BorderLayout.SOUTH);
add(panel3);
JDBC jdbc=new JDBC();
jdbc.fetchData(model);
//按键监听器
button1.addActionListener( this);
button2.addActionListener( this);
button3.addActionListener( this);
button4.addActionListener( this);
}
@Override
public void actionPerformed(ActionEvent e){
SQLHelp sqlhelp=new SQLHelp();
//添加
if(e.getSource()==button1){
try{
sqlhelp.addStudent(field1.getText(),field2.getText(),field3.getText(),field4.getText(),field5.getText(),field6.getText());
JOptionPane.showMessageDialog(Windows1.this,"添加成功");
}catch (SQLException e1){
if(e1.getSQLState().equals("23000")){
JOptionPane.showMessageDialog(Windows1.this,"添加失败,该生已存在");
}
e1.printStackTrace();
}
String[] data1={field1.getText(),field2.getText(),field3.getText(),field4.getText(),field5.getText(),field6.getText()};
model.addRow(data1);
}
//删除
else if(e.getSource()==button2){
int selectedRow=table.getSelectedRow();
if(selectedRow!=-1){
String id= (String) table.getValueAt(selectedRow,0);
try{
sqlhelp.deletestudent(id);
JOptionPane.showMessageDialog(Windows1.this,"删除成功");
}catch(SQLException e2){
JOptionPane.showMessageDialog(Windows1.this,"删除失败");
e2.printStackTrace();
}
model.removeRow(selectedRow);
}
}
//查找
else if(e.getSource()==button3){
String keyword=JOptionPane.showInputDialog(this,"请输入学生学号");
for (int i = 0; i < model.getRowCount(); i++) {
if (model.getValueAt(i, 0).toString().contains(keyword)) {
table.setRowSelectionInterval(i, i);
}
}
}
//修改
else if (e.getSource()==button4) {
int selectedRow=table.getSelectedRow();
if(selectedRow!=-1)
{
model.setValueAt(field1.getText(),selectedRow,0);
model.setValueAt(field2.getText(),selectedRow,1);
model.setValueAt(field3.getText(),selectedRow,2);
model.setValueAt(field4.getText(),selectedRow,3);
model.setValueAt(field5.getText(),selectedRow,4);
model.setValueAt(field6.getText(),selectedRow,5);
try{
sqlhelp.changeStudent(
field1.getText(),
field2.getText(),
field3.getText(),
field4.getText(),
field5.getText(),
field6.getText()
);
JOptionPane.showMessageDialog(this,"修改成功");
} catch (SQLException e3) {
throw new RuntimeException(e3);
}
}
}
}
}
JDBC类:
import javax.swing.table.DefaultTableModel;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class JDBC {
public void fetchData(DefaultTableModel model) {
int numsrow=1;
List data=new ArrayList<>();
try {
// 注册 JDBC 驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 打开链接
Connection conn = DriverManager.getConnection
(
"jdbc:mysql://localhost:3306/MySQL",
"root",
"123456"
);
// 执行查询
Statement stmt = conn.createStatement();
String sql = "SELECT ID,Name,Gender,Age,Expertise,Class FROM student.studenttable";
ResultSet rs = stmt.executeQuery(sql);
ResultSetMetaData metaData= rs.getMetaData();
int numberOfrow=metaData.getColumnCount();
Windows1 win=new Windows1();
while(rs.next()) {
Objects[] rowDta = new Objects[numberOfrow];
String id = rs.getString("ID");
String name = rs.getString("Name");
String gender = rs.getString("Gender");
String age = rs.getString("Age");
String expertise = rs.getString("Expertise");
String room = rs.getString("Class");
String[] data1 = {id, name, gender, age, expertise, room};
model.addRow(data1);
}
// 释放资源
rs.close();
stmt.close();
conn.close();
} catch(SQLException | ClassNotFoundException e){
e.printStackTrace();
}
}
}
SQLhelp类:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class SQLHelp {
public static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
public static final String DB_URL = "jdbc:mysql://localhost:3306/MySQL";//这里的jdbc:mysql://localhost:3306/一般是固定的,MySQL根据你自己的数据库名称来修改
public static final String username = "root";//数据库用户名
public static final String password = "123456";//数据库密码
private Connection connection = null;
private PreparedStatement pStatement = null;
private ResultSet rSet = null;
// 加载驱动
// 静态初始化块
static {
//JDBC驱动
try {
Class.forName(JDBC_DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
// 链接数据库
public void connectDB() {
try {
connection = DriverManager.getConnection(DB_URL,username,password);
System.out.println("数据库链接成功");
} catch (SQLException e) {
System.out.println("数据库链接失败");
e.printStackTrace();
}
}
// 关闭资源
public void close() {
if(rSet != null) {
try {
rSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(pStatement != null) {
try {
pStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public void addStudent(String id,String name,String gender, String age,String expertise,String room) throws SQLException {
// try finally 无论是否抛出异常都将执行 finally 中的语句
try {
// 先链接到数据库
connectDB();
// sql 语句
// 静态 sql 语句需要进行字符串拼接
// 动态 sql 语句
//这里的student是我们在DataGrip创建的一个框架,studenttable是一个表的名称
String addsql = "insert into student.studenttable values(?, ?, ?, ?, ?,?)";
pStatement = connection.prepareStatement(addsql);
pStatement.setString(1, id);
pStatement.setString(2, name);
pStatement.setString(3, gender);
pStatement.setString(4, age);
pStatement.setString(5, expertise);
pStatement.setString(6,room);
pStatement.executeUpdate();
} finally {
close();
}
}
public void changeStudent(String id, String name, String gender, String age, String expertise,String room) throws SQLException {
try {
connectDB();
String changesql = "update student.studenttable set name = ?, gender = ?, age = ?, expertise = ?,class=? where id = ?";
pStatement = connection.prepareStatement(changesql);
pStatement.setString(1, name);
pStatement.setString(2, gender);
pStatement.setString(3, age);
pStatement.setString(4, expertise);
pStatement.setString(5, room);
pStatement.setString(6,id);
pStatement.executeUpdate();
} finally {
close();
}
}
public void deletestudent(String id) throws SQLException {
try {
connectDB();
String deleteString = " delete from student.studenttable where id = ?";
pStatement = connection.prepareStatement(deleteString);
pStatement.setString(1, id);
pStatement.execute();
} finally {
close();
}
}
}
三.代码运行:
运行前要:
使用JDBC之前需要先导入JDBC驱动包确定已经与数据库构建了连接
添加模块:
删除模块:
选择需要删除学生的行
点击删除键
查找模块:
找到的信息会高亮显示:
修改模块:
先输入需要修改的信息,再选择需要修改信息的行数,点击修改键
验证存储功能:
先关闭程序后,再打开
数据依旧存在。
版权声明:本文为博主作者:小羊喜欢吉拉——原创文章,版权归属原作者,如果侵权,请联系我们删除!
原文链接:https://blog.csdn.net/m0_74290434/article/details/131877795