import java.sql.*;
import java.util.*;
public class JDBCTest06 {
public static void main(String[] args) {
Map<String,String> userLoginInfo=initUI();
boolean loginSuccess= Login(userLoginInfo);
System.out.println(loginSuccess?"登录成功":"登录失败");
}
/**
* 用户登录
* @param userLoginInfo 用户登录信息
* @return false失败 true成功
*/
private static boolean Login(Map<String, String> userLoginInfo) {
boolean loginSuccess=false;
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
ResourceBundle bundle=ResourceBundle.getBundle("jdbc");
String driver=bundle.getString("driver");
String url=bundle.getString("url");
String user=bundle.getString("user");
String password=bundle.getString("password");
try {//注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//获取连接
conn= DriverManager.getConnection(url,user,password);
//获取数据库对象
stmt=conn.createStatement();
//执行sql
String sql="select* from t_user where loginName='"+userLoginInfo.get("loginName")+"'and loginPwd='"+userLoginInfo.get("loginPwd")+"'";
rs=stmt.executeQuery(sql);
//处理结果集
if(rs.next()){
loginSuccess=true;
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}finally {
//释放资源
if(rs!=null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(stmt!=null){
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
return loginSuccess;
}
private static Map<String, String> initUI() {
Scanner s=new Scanner(System.in);
System.out.print("用户名:");
String loginName=s.nextLine();
System.out.print("密码:");
String loginPwd=s.nextLine();
Map<String,String> userLoginfo=new HashMap<>();
userLoginfo.put("loginName",loginName);
userLoginfo.put("loginPwd",loginPwd);
return userLoginfo;
}
}
用户名:a
密码:a'or'1'='1
登录成功