0%

JDBC-PreparedStatement 解决SQL注入问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
* 主要解决SQL注入
* 只要用户提交的信息不参与SQL语句的编译过程,问题就解决了
* 使用java.sql.PrepareStatement
*/


public class JDBCTest07 {
public static void main(String[] args) {
//初始化一个界面
Map<String, String> userLoginInfo = initUI();
//验证登录名密码
boolean loginSuccess = login(userLoginInfo);
//输出结果
System.out.println(loginSuccess ? "登录成功" : "登录失败");
}

private static boolean login(Map<String, String> userLoginInfo) {
String loginname = userLoginInfo.get("loginName");
String loginpwd = userLoginInfo.get("loginPwd");
boolean loginSuccess = false;
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
//1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode", "root", "123");

//3.获取预编译的数据库操作对象
String sql = "select * from t_user where loginname = ? and loginpwd = ?";

ps = conn.prepareStatement(sql);
//3.5 给占位符?传值
ps.setString(1, loginname);
ps.setString(2, loginpwd);
//4.执行sql
//String sql = "select * from t_user where ";
rs = ps.executeQuery();
System.out.println(sql); //测试
//5.处理结果集
if(rs.next()) {
System.out.println(rs.getString("loginname"));
System.out.println(rs.getString("realname"));
loginSuccess = true;
}

//6.释放资源
} catch (Exception e) {
e.printStackTrace();
} finally {
if(rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}


return loginSuccess;
}

private static Map<String, String> initUI() {
Scanner in = new Scanner(System.in);
System.out.println("用户名:");
String loginName = in.nextLine();
System.out.println("密码:");
String loginPwd = in.nextLine();
Map<String, String> userLoginInfo = new HashMap<String, String>();
userLoginInfo.put("loginName", loginName);
userLoginInfo.put("loginPwd", loginPwd);
return userLoginInfo;
}
}
求大佬赏个饭