How do prepared statements prevent SQL injection better than statements?

Background: I started a project using JDBC and MYSQL to simulate a bookstore, all local. To connect to the database, I started using Statement, but I began to read that when using a query several times, simply changing its parameters, it is more efficient to use PreparedStatement for these queries. However, the advantage that I read most about was how PreparedStatements can significantly improve SQL injection.

Sources: Answers on this topic are here
Google
Professors

My question is: How does PreparedStatements prevent SQL injection better or even differently than statements when dealing with parameterized queries? I am confused because, if I understand correctly, the values ​​are still passed to the SQL statement that runs, but simply to the programmer to disinfect the input.

+4
source share
3 answers

You are right that you can do sanitation yourself and, thus, be safe from injections. But this is more error prone and therefore less secure. In other words, doing it yourself introduces more chances for errors that can lead to vulnerabilities in relation to injections.

, . , SQL ('foo'), ; MySQL ("foo"), , , MySQL.

PreparedStatement, JDBC Driver, . , , JDBC , , -, , . , , , .

, preparedStatement.setString(1, name), ( , - JDBC ) :

public void setString(int idx, String value) {
    String sanitized = ourPrivateSanitizeMethod(value);
    internalSetString(idx, value);
}

( , , JDBC -, .)

, , myUserInputVar . :

private void updateUser(int name, String id) throws SQLException {
    myStat.executeUpdate("UPDATE user SET name=" + name + " WHERE id=" + id);
}

? , , , name . " ", (, hello ' world hello '' world). , UPDATE user SET name=? WHERE id=? , PreparedStatement , ?.

+6

PreparedStatement , , - , -, SQL Injection.

:

  • JDBC , ( AFAIK MySQL Connector/J useServerPrepStmts=false, ).

  • JDBC ( ) , (, ). JDBC . .

, SQL- (, , ).

+1

, Sql , . - . , Confirmend , . .

, , . , , , . , -, ...

, . , / .

0

Source: https://habr.com/ru/post/1531046/


All Articles