import java.sql.*;
import java.util.*;
/**
* 类描述:使用PrepareStatement实现登录验证
* Author: WuChu
* Date: 2021/8/2 22:53
* Version: 1.0
*/
public class PrepareStatementTest {
public static void main(String[] args) {
//初始化界面
//新建一个用户信息Map=集合对象
Map<String,String> userInfo = Init();
//判断是否合法
boolean ok = CheckLogin(userInfo.get("uName"),userInfo.get("pWord"));
//输出结果
System.out.println(ok?"登录成功!":"账号或密码错误!");
}
/**
* 初始化界面
* @return userInfo
*/
private static Map<String,String> Init(){
System.out.println("********欢迎使用系统,请输入账号密码确认身份*******");
Scanner scanner = new Scanner(System.in);
System.out.print("请输入账号:");
String uName = scanner.next();
System.out.print("请输入密码:");
String pWord = scanner.next();
//将用户输入的用户名和密码放在Map集合中
Map<String,String> userInfo = new HashMap<>();
userInfo.put("uName",uName);
userInfo.put("pWord",pWord);
//返回Map集合
return userInfo;
}
/**
* 连接数据库,判断账号密码是否合法
* @param userName 用户输入的账号
* @param passWord 用户输入的密码
* @return TRUE or FALSE
*/
private static boolean CheckLogin(String userName,String passWord){
//先定义一些全局变量
Connection connection = null;
PreparedStatement ps = null;
ResultSet rs ;
boolean ok = false;
//资源绑定器
ResourceBundle resourceBundle = ResourceBundle.getBundle("userInfo");
String driver = resourceBundle.getString("driver");
String url = resourceBundle.getString("url");
String username = resourceBundle.getString("username");
String password = resourceBundle.getString("password");
//连接数据库
try {
//1、注册数据库驱动
Class.forName(driver);
//2、获取数据库连接
connection = DriverManager.getConnection(url,username,password);
//3、获取预编译的数据库操作对象
String sql = "select * from user where username = '" + userName+"' and password = '"+ passWord +"'";
ps = connection.prepareStatement(sql);
//4、执行SQL语句
rs = ps.executeQuery();
if(rs.next()){
ok = true;
}
} catch (Exception e) {
e.printStackTrace();
}finally {
//6、关闭连接
if(ps!=null){
try {
ps.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
return ok;
}
}
使用JDBC实现简单登录验证
于 2021-08-03 13:21:50 首次发布