java实验:数据库应用(idea+mysql+php)

设计用户注册和登录界面,实现用户注册和登录操作。

  1. 设计用户注册/登录界面;
  2. 使用工具在MySQL中创建user表,包括学号、姓名、密码、专业、班级;
  3. 实现注册操作:在user表中插入一条新纪录,但学号不能重复;
  4. 实现登录操作:使用输入的学号和密码在user表中查找,查找成功,弹出消息框显示“登录成功”,不成功,则回到输入界面;使用对象文件记住在本机登录的用户名,显示在用户名组合框中。

一、首先去官网下载mysql。

java实验:数据库应用(idea+mysql+php)_第1张图片

这两个建议一起下,接着是配置环境,可以搜一下配置教程。

java实验:数据库应用(idea+mysql+php)_第2张图片启动如上图所示的mysql和apache服务。

java实验:数据库应用(idea+mysql+php)_第3张图片

点击创建数据库。java实验:数据库应用(idea+mysql+php)_第4张图片

根据提示填写,我这里的数据库名称是student,用户名ly,密码123456,最后点击确认。

接着转到mysql,java实验:数据库应用(idea+mysql+php)_第5张图片

找到连接,点击mysql,会有一下窗户:

java实验:数据库应用(idea+mysql+php)_第6张图片

就依次按刚创建的数据库填写连接名,用户名,密码,其他不用改动,点击确定。

、打开创建好的连接,新建表

java实验:数据库应用(idea+mysql+php)_第7张图片

点击保存。

java实验:数据库应用(idea+mysql+php)_第8张图片

继续保存,ctrl+s。

、代码部分

代码是在idea中编写,首先要下载驱动文件mysql-connector-j-8.2.0.jar,mysql-connector-java下载_在下是小白的博客-CSDN博客

下载之后,把mysql-connector-j-8.2.0.jar复制到项目中

java实验:数据库应用(idea+mysql+php)_第9张图片

java实验:数据库应用(idea+mysql+php)_第10张图片

点击project structure,进入找到modules,点加号选第一个。

java实验:数据库应用(idea+mysql+php)_第11张图片

找到刚刚导入的mysql-connector-j-8.2.0.jar,双击点ok就可以了。

然后新建类粘贴一下代码:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;

public class UserRegistrationLogin extends JFrame {
    private JTextField studentIdField;
    private JPasswordField passwordField;
    private JTextField nameField;
    private JTextField majorField;
    private JTextField classField;
    private JComboBox usernameComboBox;

    private Connection conn;

    public UserRegistrationLogin() {
        super("User Registration and Login");
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setSize(400, 300);
        this.setLocationRelativeTo(null);

        JPanel panel = new JPanel(new GridLayout(6, 2));

        JLabel studentIdLabel = new JLabel("Student ID:");
        studentIdField = new JTextField();
        JLabel passwordLabel = new JLabel("Password:");
        passwordField = new JPasswordField();
        JLabel nameLabel = new JLabel("Name:");
        nameField = new JTextField();
        JLabel majorLabel = new JLabel("Major:");
        majorField = new JTextField();
        JLabel classLabel = new JLabel("Class:");
        classField = new JTextField();
        JLabel usernameLabel = new JLabel("Username:");
        usernameComboBox = new JComboBox<>();

        JButton registerButton = new JButton("Register");
        JButton loginButton = new JButton("Login");

        panel.add(studentIdLabel);
        panel.add(studentIdField);
        panel.add(passwordLabel);
        panel.add(passwordField);
        panel.add(nameLabel);
        panel.add(nameField);
        panel.add(majorLabel);
        panel.add(majorField);
        panel.add(classLabel);
        panel.add(classField);
        panel.add(usernameLabel);
        panel.add(usernameComboBox);
        panel.add(registerButton);
        panel.add(loginButton);

        this.getContentPane().add(panel);

        registerButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                registerUser();
            }
        });

        loginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                loginUser();
            }
        });

        try {
            String driver = "com.mysql.cj.jdbc.Driver";
            String url = "jdbc:mysql://localhost/student?user=ly&password=123456";
            Class.forName(driver);
            conn = DriverManager.getConnection(url);

            loadUsernames();
        } catch (ClassNotFoundException | SQLException ex) {
            ex.printStackTrace();
        }
    }

    private void registerUser() {
        String studentId = studentIdField.getText();
        String password = new String(passwordField.getPassword());
        String name = nameField.getText();
        String major = majorField.getText();
        String className = classField.getText();

        if (studentId.isEmpty() || password.isEmpty() || name.isEmpty() || major.isEmpty() || className.isEmpty()) {
            JOptionPane.showMessageDialog(this, "Please fill in all fields");
            return;
        }

        try {
            PreparedStatement stmt = conn.prepareStatement("INSERT INTO student (student_id, name, password, major, class) VALUES (?, ?, ?, ?, ?)");
            stmt.setString(1, studentId);
            stmt.setString(2, name);
            stmt.setString(3, password);
            stmt.setString(4, major);
            stmt.setString(5, className);
            stmt.executeUpdate();

            JOptionPane.showMessageDialog(this, "Registration successful");

            studentIdField.setText("");
            passwordField.setText("");
            nameField.setText("");
            majorField.setText("");
            classField.setText("");

            loadUsernames();
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "Registration failed: " + ex.getMessage());
        }
    }

    private void loginUser() {
        String studentId = studentIdField.getText();
        String password = new String(passwordField.getPassword());

        try {
            PreparedStatement stmt = conn.prepareStatement("SELECT * FROM student WHERE student_id = ? AND password = ?");
            stmt.setString(1, studentId);
            stmt.setString(2, password);
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                String name = rs.getString("name");
                JOptionPane.showMessageDialog(this, "Login successful. Welcome, " + name + "!");

                // Remember the username for future logins
                String selectedUsername = (String) usernameComboBox.getSelectedItem();
                if (selectedUsername == null || !selectedUsername.equals(name)) {
                    usernameComboBox.addItem(name);
                    usernameComboBox.setSelectedItem(name);
                }

                studentIdField.setText("");
                passwordField.setText("");
            } else {
                JOptionPane.showMessageDialog(this, "Login failed. Please check your student ID and password.");
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "Login failed: " + ex.getMessage());
        }
    }

    private void loadUsernames() {
        try {
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT DISTINCT name FROM student");

            usernameComboBox.removeAllItems();
            while (rs.next()) {
                String name = rs.getString("name");
                usernameComboBox.addItem(name);
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                UserRegistrationLogin frame = new UserRegistrationLogin();
                frame.setVisible(true);
            }
        });
    }
}

效果展示:

java实验:数据库应用(idea+mysql+php)_第12张图片

你可能感兴趣的:(数据库,java)