用JAVA自带的GUI写一个按钮,使按钮链接数据库

实现标准:点击按钮后,会自动显示数据库内容
最好有讲解太感谢了急急急😭😭😭

所需数据库驱动如下代码是操作mysql数据库:

package ui;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class Test {
    
    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        initialize();
    }

    private void initialize() {
        JFrame frame = new JFrame();
        frame.setTitle("连接数据库");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setBackground(new Color(176, 196, 222));
        frame.setBounds(100, 100, 450, 300);
        frame.getContentPane().setLayout(null);
        // 窗口显示在页面中间
        frame.setLocationRelativeTo(null);
        // 窗口不允许调整大小
        frame.setResizable(false);
        JButton button = new JButton("连接");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Connection conn = null;
                try {
                    Class.forName("com.mysql.jdbc.Driver");
                    conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/teachersystem_db", "root", "root");
                    if (conn != null) {
                        JOptionPane.showMessageDialog(null, "连接成功", "连接提示", JOptionPane.INFORMATION_MESSAGE);
                        frame.dispose(); // 关闭当前页面
                    } else {
                        JOptionPane.showMessageDialog(null, "连接失败", "连接提示", JOptionPane.ERROR_MESSAGE);
                    }
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } finally {
                    if (conn != null) {
                        try {
                            conn.close();
                        } catch (SQLException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        }
                    }
                }

            }
        });
        button.setBackground(Color.LIGHT_GRAY);
        button.setBounds(155, 213, 113, 27);
        frame.getContentPane().add(button);
        frame.setVisible(true);

    }

}


运行效果:
img

思路:
1.创建类,继承JFRAME,添加JButton按钮,添加Action事件监听
2.使用Connection对象创建数据库连接。
Class.forName(driver);
Connection url = DriverManager.getConnection(url,username,password);