PreparedStatement 和单纯的单引号不同

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容