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注入的'會被轉(zhuǎn)義成'' 字符串的單引號, 而拼接則不會
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
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者