package com.cqust;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
//模拟用户登录,验证成功还是失败
public class JDBCTest05 {
public static void main(String[] args) throws Exception {
//初始化界面,返回用户输入的信息,使用map集合存储
Map
//登录方法,返回值是布尔类型
Boolean loginInfo = login(userInfo);
System.out.println(loginInfo ? "登录成功":"登录失败");
}
public static Map initLogin(){
Map userInfo = new HashMap<>();
System.out.print("请输入你的用户名:");
Scanner scanner = new Scanner(System.in);
String username = scanner.next();
System.out.print("请输入你的密码:");
String userpwd = scanner.next();
userInfo.put("username",username);
userInfo.put("userpwd",userpwd);
return userInfo;
}
public static boolean login(Map map) throws Exception{
String username = map.get("username");
String userpwd = map.get("userpwd");
boolean loginInfo = false;
//1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/cqust_db",
"root","hch1");
//3.获取数据库操作对象
Statement statement = connection.createStatement();
//4.写sql,执行sql
String sql = "select username,userpwd from t_user_login where username = ""+username+"" and userpwd = ""+userpwd+""";
ResultSet resultSet = statement.executeQuery(sql);
//5.这里只需要看是否有数据,如果查询到数据,则登录成功,直接loginInfo = true;
if (resultSet.next()){
loginInfo = true;
}
//6.关闭资源
if (resultSet!=null){
resultSet.close();
}
if (statement!=null){
statement.close();
}
if (connection!=null){
connection.close();
}
return loginInfo;
}
}