How does a PreparedStatement avoid or prevent SQL injection?

前端 未结 10 1684
再見小時候
再見小時候 2020-11-22 05:21

I know that PreparedStatements avoid/prevent SQL Injection. How does it do that? Will the final form query that is constructed using PreparedStatements will be a string or o

10条回答
  •  孤街浪徒
    2020-11-22 05:45

    Consider two ways of doing the same thing:

    PreparedStatement stmt = conn.createStatement("INSERT INTO students VALUES('" + user + "')");
    stmt.execute();
    

    Or

    PreparedStatement stmt = conn.prepareStatement("INSERT INTO student VALUES(?)");
    stmt.setString(1, user);
    stmt.execute();
    

    If "user" came from user input and the user input was

    Robert'); DROP TABLE students; --
    

    Then in the first instance, you'd be hosed. In the second, you'd be safe and Little Bobby Tables would be registered for your school.

提交回复
热议问题