package com.luojie;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Scanner;
public class UserLogin02 {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
//初始化界面
Map<String,String> userLoginInfo = initUi();
//用户登录
boolean loginSuccess = login(userLoginInfo);
//输出结果
System.out.println(loginSuccess?"登录成功":"登录失败");
}
//登录的方法
/*
false 登录失败 true 登录成功
*/
private static boolean login(Map<String, String> userLoginInfo) throws SQLException {
//JDBC代码
boolean loginSuccess = false;
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
ResourceBundle bundle = ResourceBundle.getBundle("db");
String driver = bundle.getString("driver");
String url = bundle.getString("url");
String user = bundle.getString("user");
String password = bundle.getString("password");
try {
Class.forName(driver);
conn = DriverManager.getConnection(url,user,password);
System.out.println("数据库连接成功"+ conn);
String loginName = userLoginInfo.get("loginName");
String loginPassword = userLoginInfo.get("loginPwd");
// 防止sql注入
String sql = "select * from t_user_login where loginName= ?and loginPassword=?";
ps = conn.prepareStatement(sql);
// 传值 第一个?下标是1 第二个?下标是2 JDBC中所有下标从1开始
ps.setString(1, userLoginInfo.get("loginName"));
ps.setString(2, userLoginInfo.get("loginPwd"));
rs = ps.executeQuery();
if(rs.next()){
loginSuccess = true;
}else{
loginSuccess = false;
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
if(rs !=null){
try {
rs.close();
}catch (Exception e){
e.printStackTrace();
}
}
if(ps !=null){
try {
ps.close();
}catch (Exception e){
e.printStackTrace();
}
}
if(conn !=null){
try {
conn.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
return loginSuccess;
}
//初始化界面的方法
private static Map<String, String> initUi() {
Scanner s = new Scanner(System.in);
System.out.println("用户名: ");
String loginName = s.nextLine();
System.out.println("密码: ");
String loginPwd = s.nextLine();
Map<String,String> userLoginInfo = new HashMap<>();
userLoginInfo.put("loginName",loginName);
userLoginInfo.put("loginPwd",loginPwd);
System.out.println(userLoginInfo);
return userLoginInfo;
}
}
JDBC连接MySQL案例02
最新推荐文章于 2024-04-26 13:29:49 发布