java连接mysql进行用户的登录和注册(简易版)

java:IDEA

数据库:mysql 8.0

TestMain类(运行程序的起点):

public class TestMain {
    public static void main(String[] args) {
        new login().setVisible(true);
    }
}

login类(用户登录界面):

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import static java.lang.System.exit;

public class login extends JFrame{

    private JButton loginLbl;
    private JPasswordField mimaTfd;
    private JTextField nameTfd;
    private JButton exitLbl;
    private JButton registerLbl;

    public login(){
        init();
    }

    private void init(){
        //设置窗体大小
        setSize(650,400);
        //显示设置 默认居中显示
        setLocationRelativeTo(null);
        //设置绝对布局
        setLayout(null);
        //设置标题
        setTitle("哔哩哔哩模拟器---用户登录");
        //设置关闭窗体时退出程序
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        //设置禁止改变窗体大小
        setResizable(false);
        //设置背景
        getContentPane().setBackground(Color.decode("#f1f9f9"));

        //创建“哔哩哔哩模拟器”标签
        JLabel titleLbl = new JLabel("哔哩哔哩模拟器");
        titleLbl.setBounds(170, 30, 400, 100);
        Font font1 = new Font("楷体", Font.PLAIN+Font.BOLD, 50);
        titleLbl.setFont(font1);
        add(titleLbl);
        //创建“用户名”标签
        JLabel nameLbl = new JLabel("用户名:");
        nameLbl.setBounds(200, 140, 80, 50);
        Font font = new Font("楷体", Font.PLAIN, 20);
        nameLbl.setFont(font);
        add(nameLbl);
        //创建用户名输入框
        nameTfd = new JTextField("");
        nameTfd.setBounds(280, 140, 140, 50);
        nameTfd.setFont(font);
        add(nameTfd);
        //创建“密码”标签
        JLabel mimaLbl = new JLabel("密码:");
        mimaLbl.setBounds(210, 195, 80, 50);
        mimaLbl.setFont(font);
        add(mimaLbl);
        //创建密码输入框
        mimaTfd = new JPasswordField("");
        mimaTfd.setBounds(280, 195, 140, 50);
        mimaLbl.setFont(font);
        add(mimaTfd);
        //创建“登录”按钮
        loginLbl = new JButton("登录");
        loginLbl.setBounds(150, 290, 70, 40);
        Font font2 = new Font("楷体", Font.PLAIN, 15);
        loginLbl.setFont(font2);
        add(loginLbl);
        //创建“注册”按钮
        registerLbl = new JButton("注册");
        registerLbl.setBounds(300, 290, 70, 40);
        registerLbl.setFont(font2);
        add(registerLbl);
        //创建“退出”按钮
        exitLbl = new JButton("退出");
        exitLbl.setBounds(445, 290, 70, 40);
        exitLbl.setFont(font2);
        add(exitLbl);

        //login页面跳转-----MainFrame页面----iflogin方法
        loginLbl.addActionListener(new ActionListener() {
            public void actionPerformed (ActionEvent e){
                if (iflogin(nameTfd.getText(), mimaTfd.getText())) {
                    JOptionPane.showMessageDialog(null, "登陆成功!", "消息", -1);
                    new MainFrame().setVisible(true);
                    setVisible(false);
                } else {
                    JOptionPane.showMessageDialog(null, "登陆失败!", "消息", -1);
                }
            }
        });

        //login页面跳转-----register页面
        registerLbl.addActionListener(new ActionListener() {
            public void actionPerformed (ActionEvent e){
                new register().setVisible(true);
                setVisible(false);
            }
        });

        //login页面跳转-----终止程序
        exitLbl.addActionListener(new ActionListener() {
            public void actionPerformed (ActionEvent e){
                JOptionPane.showMessageDialog(null, "成功退出程序!", "消息", -1);
                exit(0);
            }
        });
    }

    //判断是否可以登录---在数据库中对比账号密码
    public static boolean iflogin(String name, String password) {
        if (name == null && password == null) {//判断输入是否合理
            return false;
        }
        Connection con = null;//代表数据库连接
        PreparedStatement pre = null;//用于执行预编译的SQL语句
        ResultSet resultSet = null;//存储了从数据库查询返回的结果集
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost:3307/demo", "root", "123456");
            String sql = "SELECT * FROM login WHERE name=? AND password=?";//编写SQL语句
            pre = con.prepareStatement(sql);//将SQL查询语句作为参数传入
            pre.setString(1, name);//设置第参数的值,(参数的位置,要设置的值)
            pre.setString(2, password);
            resultSet = pre.executeQuery();//执行查询,并将返回的结果集赋值
            return resultSet.next();//判断结果集中是否有下一条记录
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}

register类(用户注册界面):

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

public class register extends JFrame implements ActionListener {

    private JTextField nametfd;
    private JPasswordField mimatfd;
    private JPasswordField mimatfd2;
    private ResultSet rs;

    public register(){
        init();
    }
    public void init() {
        //设置窗体大小
        setSize(400,650);
        //显示设置 默认居中显示
        setLocationRelativeTo(null);
        //设置绝对布局
        setLayout(null);
        //设置标题
        setTitle("哔哩哔哩模拟器---用户注册");
        //设置关闭窗体时退出程序
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        //设置禁止改变窗体大小
        setResizable(false);
        //设置背景
        getContentPane().setBackground(Color.decode("#f1f9f9"));
        //创建“用户注册”标签
        JLabel titleLbl = new JLabel("b站用户注册");
        titleLbl.setBounds(60, 50, 300, 150);
        Font font2 = new Font("楷体", Font.PLAIN, 50);
        titleLbl.setFont(font2);
        add(titleLbl);
        //创建“用户名”标签
        JLabel nameLbl = new JLabel("用户名:");
        nameLbl.setBounds(80, 200, 90, 50);
        Font font = new Font("楷体", Font.PLAIN, 25);
        nameLbl.setFont(font);
        add(nameLbl);
        //创建用户名输入框
        nametfd = new JTextField("");
        nametfd.setBounds(180, 200, 130, 50);
        nametfd.setFont(font);
        add(nametfd);
        //创建“密码”标签
        JLabel mimaLbl = new JLabel("密码:");
        mimaLbl.setBounds(90, 260, 130, 50);
        mimaLbl.setFont(font);
        add(mimaLbl);
        //创建密码输入框
        mimatfd = new JPasswordField("");
        mimatfd.setBounds(180, 260, 130, 50);
        mimaLbl.setFont(font);
        add(mimatfd);
        //创建“确认密码”标签
        JLabel mimaLbl2 = new JLabel("确认密码:");
        mimaLbl2.setBounds(65, 320, 130, 50);
        mimaLbl2.setFont(font);
        add(mimaLbl2);
        //创建 确认密码 输入框
        mimatfd2 = new JPasswordField("");
        mimatfd2.setBounds(180, 320, 130, 50);
        mimaLbl.setFont(font);
        add(mimatfd2);
        //确定 按钮
        JButton sureBtn = new JButton("确定");
        sureBtn.setBounds(60,500,100,50);
        Font font1 = new Font("楷体", Font.PLAIN, 20);
        sureBtn.setFont(font1);
        add(sureBtn);
        //取消 按钮
        JButton exitBtn = new JButton("取消");
        exitBtn.setBounds(230,500,100,50);
        exitBtn.setFont(font1);
        add(exitBtn);

        //register页面跳转-----login页面
        exitBtn.addActionListener(new ActionListener() {
            public void actionPerformed (ActionEvent e){
                setVisible(false);
                new login().setVisible(true);
            }
        });

        //给按钮绑定监听
        sureBtn.addActionListener(this);
    }

    //监听到被点击时,代码执行这里
    @Override
    public void actionPerformed(ActionEvent actionEvent) {
        actionPerformed();
        setVisible(false);
        new login().setVisible(true);
    }

    //注册
    public void actionPerformed() {
        String name = nametfd.getText();
        String password = mimatfd.getText();
        String password2 = mimatfd2.getText();

        if (nametfd.getText().isEmpty() || mimatfd.getText().isEmpty() ||
                mimatfd2.getText().isEmpty()) {
            JOptionPane.showMessageDialog(null, "账号或密码不能为空");
            return;
        }
        Connection con = null;
        PreparedStatement pre = null;
        rs = null;//存储了从数据库查询返回的结果集
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost:3307/demo", "root", "123456");

            //检查用户名是否已存在在
            String sql = "SELECT * FROM login WHERE name=? ";
            pre = con.prepareStatement(sql);
            pre.setString(1, name);
            rs = pre.executeQuery();//执行查询,并将返回的结果集赋值

            if (rs.next()) {       //判断用户名是否重复
                JOptionPane.showMessageDialog(null, "用户名已经存在");
            }
            else {
                if (password2.equals(password)) {   //如果两次输入密码一致
                    //数据库执行操作
                    String sql2 = "INSERT INTO login(name, password) VALUES (?, ?)";
                    pre = con.prepareStatement(sql2);
                    pre.setString(1, name);
                    pre.setString(2, password);
                    pre.executeUpdate();
                    JOptionPane.showMessageDialog(null, "注册成功");

                    this.setVisible(false);
                }
                else {
                    JOptionPane.showMessageDialog(null, "两次密码输入不一致");
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException("注册失败!", e);
        }finally {
            try {
                // 关闭连接和释放资源
                if (rs != null) rs.close();
                if (pre != null) pre.close();
                if (con != null) con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

MainFrame类(登陆成功后显示的界面):

import javax.swing.*;
import java.awt.*;

public class MainFrame extends JFrame{
    public  MainFrame(){
        init();
    }
    private void init(){
        setSize(650,400);
        setLocationRelativeTo(null);
        setLayout(null);
        setTitle("欢迎来到哔哩哔哩!");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(false);
        getContentPane().setBackground(new Color(255, 122, 212, 225));

        //创建“哔哩哔哩模拟器”标签
        JLabel titleLbl = new JLabel("哔哩哔哩模拟器");
        titleLbl.setBounds(150, 30, 400, 100);
        Font font1 = new Font("楷体", Font.PLAIN+Font.BOLD, 50);
        titleLbl.setFont(font1);
        add(titleLbl);

    }
}

mysql设置:

运行结果:

代码可运行

计算机小白,请多指教

  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现Java连接MySQL实现QQ登录注册功能,需要以下步骤: 1. 在MySQL中创建一个数据库,并创建用户表和登录表。 2. 下载并安装MySQL的JDBC驱动程序。 3. 在Java中编写代码连接MySQL数据库。 4. 编写Java代码实现用户注册功能,将用户信息插入到用户表中。 5. 编写Java代码实现用户登录功能,查询用户表中是否存在该用户的信息。 下面是一个示例代码: ``` import java.sql.*; public class QQLoginRegister { private static final String url = "jdbc:mysql://localhost:3306/qquser?useSSL=false"; private static final String user = "root"; private static final String password = "123456"; public static void main(String[] args) { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(url, user, password); // 用户注册 String username = "test"; String password = "123456"; ps = conn.prepareStatement("insert into user (username, password) values (?, ?)"); ps.setString(1, username); ps.setString(2, password); ps.executeUpdate(); // 用户登录 String loginUsername = "test"; String loginPassword = "123456"; ps = conn.prepareStatement("select * from user where username = ? and password = ?"); ps.setString(1, loginUsername); ps.setString(2, loginPassword); rs = ps.executeQuery(); if (rs.next()) { System.out.println("登录成功"); } else { System.out.println("登录失败"); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (rs != null) { rs.close(); } if (ps != null) { ps.close(); } if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } } } ``` 在该示例代码中,我们通过JDBC连接MySQL数据库,并实现了用户注册登录功能。其中,我们通过PreparedStatement对象来动态地设置SQL语句中的参数,以防止SQL注入攻击。同时,我们还使用了try-catch-finally语句块来确保资源的正确释放。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值