public class TestPrepared {
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?serverTimezone=UTC&profileSQL=true", "test", "test");
String username = "admin' OR '1'='1";
String password = "123";
String sql = "SELECT * FROM users WHERE username = '" + username + "' AND password = '" + password + "'";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(sql);
System.out.println(rs.toString());
sql = "SELECT * FROM users WHERE username = ? AND password = ?";
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setString(1, username);
pstmt.setString(2, password);
rs = pstmt.executeQuery();
System.out.println(rs.toString());
} catch (SQLException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
}
使用PreparedStatement sql注入的'会被转义成'' 字符串的单引号, 而拼接则不会
SELECT * FROM users WHERE username = 'admin' OR '1'='1' AND password = '123';
SELECT * FROM users WHERE username = 'admin'' OR ''1''=''1' AND password = '123';
具体输出日志
[Created on: Tue May 14 22:02:01 CST 2024, duration: 1, connection-id: 15, statement-id: 0, resultset-id: 0, at test.prepared.TestPrepared.main(TestPrepared.java:24)]
Tue May 14 22:02:01 CST 2024 INFO: [FETCH] [Created on: Tue May 14 22:02:01 CST 2024, duration: 0, connection-id: 15, statement-id: 0, resultset-id: 0, at test.prepared.TestPrepared.main(TestPrepared.java:24)]
com.mysql.cj.jdbc.result.ResultSetImpl@2d2e5f00
com.mysql.cj.jdbc.result.ResultSetImpl@568bf312