小项目介绍:数据库中原本存储有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;
}
}
分享一下我在写这个小项目中遇到的问题吧:
这个主要是没有获取数据库操作对象,即缺少这一步:
Statement statement=null;
statement=connection.createStatement();
还遇到另外一种情况也是空指针异常:
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***