利用jdbc实现登录系统~~

小项目介绍:数据库中原本存储有username,password和id,通过输入username和password来判断该用户信息是否存在于数据库中,并验证是否登录成功。

这是表:

在这里插入图片描述

来展示下代码,查询条件可变,可自行尝试

import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Login {
public static void main(String[] args) {
Map<String ,String> Login=LoginUI();
boolean islogin=login(Login);
System.out.println(islogin?“登陆成功”:“登陆失败”);

}

//传入key value
private static boolean login(Map<String, String> login) {
boolean loginSuccess=false;
Connection connection=null;
Statement statement=null;
ResultSet resultSet=null;

    try {
        Class.forName("com.mysql.cj.jdbc.Driver");
        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/user?serverTimezone=UTC", "root", "33333333");
        statement=connection.createStatement();
        String sql="select * from tuser where loginName= '"+login.get("loginName")+"' and loginPassword='"+login.get("loginPassword")+"'";
        resultSet= statement.executeQuery(sql);
        if(resultSet.next())
        {
            loginSuccess=true;
        }
        return loginSuccess;

    } catch (ClassNotFoundException | SQLException e) {
        e.printStackTrace();
    }finally {
        try {
            resultSet.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            statement.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            connection.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    return  false;
}
private static Map<String, String> LoginUI() {
    System.out.println("请输入账号:");
    Scanner input =new Scanner(System.in);
    String username=input.nextLine();
    System.out.println("请输入密码");
    String password=input.nextLine();
    Map<String,String> Login=new HashMap<>();
    Login.put("loginName",username);
    Login.put("loginPassword",password);
    return  Login;
}

}

分享一下我在写这个小项目中遇到的问题吧:

  1. 在这里插入图片描述
    这个主要是没有获取数据库操作对象,即缺少这一步:
    Statement statement=null;
    statement=connection.createStatement();
    还遇到另外一种情况也是空指针异常:
    这里我把resultSet写出了别的单词,导致下面.next()获取到了空对象

2.check the manual that corresponds to your MySQL server version for the right syntax to use near ‘-user) where loginName=‘天羽毛’ and loginPassword=‘123456’’ 这个原因是 表名字不规范我开始使用的是t-user,对表命名规范感兴趣的同学可自行百度

就这样吧~~拜

                                                                                                                           ***风离QQ:1906249647***
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值