Home > Database > Mysql Tutorial > How to Safely Parameterize the IN Clause in Android SQL Queries?

How to Safely Parameterize the IN Clause in Android SQL Queries?

Barbara Streisand
Release: 2025-01-18 17:32:09
Original
513 people have browsed it

How to Safely Parameterize the IN Clause in Android SQL Queries?

IN clause and placeholder conundrum in Android SQL queries

In Android, executing SQL queries often involves using parameterized placeholders to prevent SQL injection vulnerabilities. This occurs when an IN clause is used. Consider the following query:

<code>String names = "name1', 'name2";   // 动态生成
String query = "SELECT * FROM table WHERE name IN (?)";
Cursor cursor = mDb.rawQuery(query, new String[]{names});</code>
Copy after login

However, Android cannot replace the question mark with the provided value. Alternatively, you can choose:

<code>String query = "SELECT * FROM table WHERE name IN (" + names + ")";
Cursor cursor = mDb.rawQuery(query, null);</code>
Copy after login

While this approach eliminates the SQL injection threat, it fails to properly parameterize the query.

Parameterized IN clause

To achieve parameterization while avoiding the risk of injection, consider using strings with placeholder patterns:

<code>String query = "SELECT * FROM table WHERE name IN (" + makePlaceholders(names.length) + ")";
Cursor cursor = mDb.rawQuery(query, names);</code>
Copy after login
The

makePlaceholders(len) function generates a string containing the required number of question marks, separated by commas. This allows queries to be safely inserted without affecting parameterization.

Implementation of makePlaceholders(len):

<code>String makePlaceholders(int len) {
    if (len < 1) {
        throw new IllegalArgumentException("Length must be > 0");
    }
    StringBuilder sb = new StringBuilder(len * 2 - 1);
    sb.append("?");
    for (int i = 1; i < len; i++) {
        sb.append(",?");
    }
    return sb.toString();
}</code>
Copy after login

Please note that SQLite generally supports up to 999 host parameters, except in some specific Android versions.

The above is the detailed content of How to Safely Parameterize the IN Clause in Android SQL Queries?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template