登录验证-对接数据库(Java通用)

木子空间Pro 2023-07-18 17:37:35

效果

img

img

数据库表

/*
 Navicat MySQL Data Transfer

 Source Server         : 1761
 Source Server Type    : MySQL
 Source Server Version : 80017
 Source Host           : localhost:3306
 Source Schema         : hw_book_sys

 Target Server Type    : MySQL
 Target Server Version : 80017
 File Encoding         : 65001

 Date: 18/07/2023 17:31:20
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  `password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, '1', '1');
INSERT INTO `user` VALUES (2, '2', '2');
INSERT INTO `user` VALUES (3, '3', '3');

SET FOREIGN_KEY_CHECKS = 1;

关键代码

  1. 窗体
package com.student;

import com.student.tools.DataUtils;

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

class LoginWindow extends JFrame implements ActionListener {
    private JTextField userField;
    private JPasswordField passwordField;
    private JButton loginButton, cancelButton;


    public LoginWindow() {
        setTitle("用户登录");

        // 创建输入框和按钮
        userField = new JTextField(20);
        passwordField = new JPasswordField(20);
        loginButton = new JButton("登录");
        cancelButton = new JButton("取消");

        // 添加事件监听器
        loginButton.addActionListener(this);
        cancelButton.addActionListener(this);

        // 创建面板并添加组件
        JPanel panel1 = new JPanel(new GridLayout(2, 1, 5, 5));
        panel1.add(new JLabel("用户:"));
        panel1.add(new JLabel("密码:"));

        JPanel panel2 = new JPanel(new GridLayout(2, 1, 5, 5));
        panel2.add(userField);
        panel2.add(passwordField);

        JPanel panel3 = new JPanel(new FlowLayout());
        panel3.add(loginButton);
        panel3.add(cancelButton);

        // 添加组件到窗口
        Container container = getContentPane();
        container.setLayout(new BorderLayout(5, 5));
        container.add(panel1, BorderLayout.WEST);
        container.add(panel2, BorderLayout.CENTER);
        container.add(panel3, BorderLayout.SOUTH);

        // 设置窗口属性
        setSize(300, 150);
        setLocationRelativeTo(null);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    // 实现事件监听器接口
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == loginButton) {  // 登录
            String user = userField.getText().trim();
            String pass = new String(passwordField.getPassword()).trim();
            if (user.isEmpty() || pass.isEmpty()) {  // 用户名或密码为空
                JOptionPane.showMessageDialog(this, "用户名或密码不能为空!");
            } else if (isOK(user,pass)) {  // 用户名和密码正确
                dispose();  // 关闭当前窗口
                new DemoWin2().setVisible(true);  // 打开表格窗口
            } else {  // 用户名或密码错误
                JOptionPane.showMessageDialog(this, "用户名或密码错误!");
            }
        } else if (e.getSource() == cancelButton) {  // 取消
            System.exit(0);  // 退出程序
        }
    }

    public boolean isOK(String user,String password){
        String sql = "select * from user where username=?";
        try {
            ResultSet set = DataUtils.query(sql, new Object[]{user});
            if (set.next()) {
                String name = set.getString(2);
                String pwd = set.getString(3);
                if (user.equals(name) && password.equals(pwd)) {
                    return true;
                }
            } else {
                return false;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return false;
    }
}


  1. 数据库连接
package com.student.tools;

import java.sql.*;

public class ConnSQL {
    // 获取连接通道
    // Connection 
    public static Connection getConnection() {
        Connection conn = null;
        // 1.加载驱动类
        try {
            // Mysql驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 获取连接通道
            String url ="jdbc:mysql://localhost:3306/hw_book_sys?useSSL=false&serverTimezone=Asia/Shanghai";
            String user = "root";
            String password = "root";
            conn = DriverManager.getConnection(url,user,password);
        } catch (ClassNotFoundException  e) {
            // 1.类名错误 2.外部jar没有引用
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return conn;
    }
    // 关闭资源
    public  static void closeDB(ResultSet rs,Statement pst,Connection conn) {
        try {
            if(rs!=null) {
                rs.close();
            }
            if(pst!=null) {
                pst.close();
            }
            if(conn!=null) {
                conn.close();
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        System.out.println(ConnSQL.getConnection());
    }
}


  1. 工具类
package com.student.tools;
import java.sql.*;

public class DataUtils {
    static Connection conn= ConnSQL.getConnection();
    
    public static ResultSet query(String sql, Object[] objects) throws SQLException {
        PreparedStatement pst = conn.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
        ResultSet resultSet=null;
//        判断Object是否为空,为空直接执行sql语句
        if (objects == null) {
            resultSet = pst.executeQuery();
        } else {
            for (int i = 0; i < objects.length; i++) {
                pst.setObject(i+1,objects[i]);
            }
            resultSet = pst.executeQuery();
        }
        return resultSet;
    }

}



...全文
193 回复 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

14

社区成员

发帖
与我相关
我的任务
社区描述
学习交流,在线答疑,远程协助,程序定制与DIY,直接私聊群主即可,忙碌时段回复有延迟!
后端经验分享程序人生 个人社区 广东省·广州市
社区管理员
  • 木子空间Pro
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧