package com.cqust;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class JDBCTest06 {
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.获取数据库操作对象,预编译sql
String sql = "select username,userpwd from t_user_login where username = ? and userpwd = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1,username);
statement.setString(2,userpwd);
//4.执行sql
//String sql = "select username,userpwd from t_user_login where username = ""+username+"" and userpwd = ""+userpwd+""";
ResultSet resultSet = statement.executeQuery();
//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;
}
}