1、方法的思想,提供初始化界面的方法,提供验证用户名密码的方法;
2、用反射获取连接,优化第一种写法;
3、利用PowerDesigner建表;
4、建表语句;
drop table if exists t_user;
/*==============================================================*/
/* Table: t_user */
/*==============================================================*/
create table t_user
(
id bigint auto_increment,
loginName varchar(255),
loginPwd varchar(255),
realName varchar(255),
primary key (id)
);
insert into t_user(loginName,loginPwd,realName) values('***','***','***');
insert into t_user(loginName,loginPwd,realName) values('***','***','***');
commit;
select * from t_user;
5、调用Map集合进行用户名密码的获取;
6、完整代码:
import com.mysql.jdbc.Driver;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Test{
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;
//JDBC准备
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
//1、注册驱动
Class.forName("com.mysql.jdbc.Driver");
// 2、获取连接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库","root","****");
// 3、获取数据库操作对象
statement = connection.createStatement();
//4、执行sql
String sql= "select * from t_user where loginName = '"+ userLoginInfo.get("userName") +"' and loginPwd = '"+ userLoginInfo.get("userPwd") +"'";
resultSet= statement.executeQuery(sql);
//5、处理结果集
if (resultSet.next()){
loginSuccess = true;
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
//6、释放资源
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return loginSuccess;
}
/**
* 初始化用户界面
* @return 用户输入的用户名和密码
*/
private static Map<String, String> initUI() {
Scanner s = new Scanner(System.in);
System.out.println("请输入用户名:");
String userName = s.nextLine();
System.out.println("请输入密码:");
String userPwd = s.nextLine();
Map<String,String> userLoginInfo = new HashMap<>();
userLoginInfo.put("userName",userName);
userLoginInfo.put("userPwd",userPwd);
return userLoginInfo;
}
}
7、结果显示;


8、SQL注入现象
密码注入了sql语句,影响判断

网友评论