How to prevent SQL injection?

First of all, SQL injection is a common security vulnerability. Hackers can attack databases and applications by injecting malicious code. Here are some basic measures to prevent SQL injection:

Database operation level

  1. Use parameterized queries: Parameterized queries can prevent SQL injection because parameterized queries filter and escape the data entered by the user, thereby protecting the query statement from attacks.
  2. Avoid dynamic splicing of SQL statements: Dynamic splicing of SQL statements is a major cause of SQL injection. To prevent SQL injection, try to avoid dynamically splicing SQL statements and instead use parameterized queries.
  3. Validate and filter user-entered data: When receiving user-entered data, data validation and filtering can effectively prevent SQL injection. For example, check whether user input contains special characters or SQL keywords and escape the input.
  4. Do not run applications with administrator privileges: To prevent SQL injection, do not run applications with administrator privileges. Applications should be assigned minimal permissions to avoid hackers exploiting injection vulnerabilities to gain administrator privileges.
  5. Update applications and databases regularly: Keeping applications and databases up to date can patch known security vulnerabilities and enhance security.

Java code level

The way to prevent SQL injection attacks is to use parameterized queries, that is, to use 预编译语句(Prepared Statement)or 存储过程(Stored Procedure)to process SQL query statements.
The advantage of using prepared statements is that it separates SQL query statements and parameters, thereby avoiding the risk of malicious users injecting malicious SQL code through parameters. At the same time, precompiled statements can effectively cache SQL query statements and improve query performance.

Here is sample code that uses prepared statements to prevent SQL injection attacks:

String sql = "SELECT * FROM users WHERE username = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, username);
ResultSet rs = pstmt.executeQuery();

In this example, we use the placeholder ? to represent the position of the parameter, and then use the setString() method to set the value of the placeholder. This ensures that the entered value will not be interpreted as SQL code, thereby avoiding the risk of SQL injection attacks.


MyBatis framework layer

Use the MyBatis ORM framework, which provides multiple ways to prevent SQL injection attacks. Here are some common methods:

1. Use parameterized queries

  • In MyBatis, using parameterized queries can avoid SQL injection attacks. The specific implementation method is to use placeholders ${}or #{}variables in the Mapper XML file to replace the variables in the query conditions, and then pass the variables into the query statement. For example: [Note]: Use placeholders
    in the code . Do not use placeholders that may lead to SQL injection risks. Use string replacement, that is, SQL splicing.#{}${}${}
<select id="getUserByName" resultType="User">
    SELECT * FROM users WHERE username = #{name}
</select>

In the above example, #{name}placeholders are used to represent variables in the query conditions name, and then getUserByNamemethods are used to execute the query.

2. Use parameter type converter

  • The parameter type converter in MyBatis can convert parameter values ​​from Java types to database types. This feature can prevent some simple SQL injection attacks. For example, if you convert a string parameter to an integer type, the SQL code in the string is escaped.
<select id="getUserById" resultType="User">
    SELECT * FROM users WHERE id = #{id, jdbcType=INTEGER}
</select>

In this example, jdbcTypeattributes are used to specify the parameter type as an integer type, which prevents malicious users from conducting SQL injection attacks by entering string type parameters.

3. Use dynamic SQL

  • Dynamic SQL in MyBatis can generate different SQL query statements based on different query conditions. This feature can avoid some simple SQL injection attacks. For example, if the query condition is a null value, then no query statement will be executed, thereby avoiding the risk of SQL injection attacks.
<select id="getUser" resultType="User">
    SELECT * FROM users 
    <where>
        <if test="name != null">
            AND username = #{name}
        </if>
        <if test="id != null">
            AND id = #{id}
        </if>
    </where>
</select>

In the above example, labels are used to determine whether the query condition is empty. If not, the corresponding SQL query statement is generated. This prevents malicious users from entering malicious SQL code to conduct SQL injection attacks.

Guess you like

Origin blog.csdn.net/Lance_welcome/article/details/129696927