Home >Database >Mysql Tutorial >How to Safely Use the IN Clause with Placeholders in SQLite for Android?

How to Safely Use the IN Clause with Placeholders in SQLite for Android?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-18 17:16:09762browse

How to Safely Use the IN Clause with Placeholders in SQLite for Android?

IN clause and placeholders

Question:

SQLite queries using IN clauses with dynamic string concatenation in Android face the following challenges:

  • Standard placeholders (?) were not replaced correctly.
  • Replacing the concatenated string directly may expose the query to the risk of SQL injection.

Solution:

To parameterize an IN clause, use a comma-delimited string of question marks whose length is equal to the number of values ​​to be replaced. Avoid using external data to ensure the validity of dynamic strings.

<code>String[] names = { "name1", "name2" }; // 动态获取值
String query = "SELECT * FROM table WHERE name IN (" + makePlaceholders(names.length) + ")";
Cursor cursor = mDb.rawQuery(query, names);</code>
<code>public static String makePlaceholders(int len) {
    if (len < 1) {
        throw new IllegalArgumentException("Length must be at least 1");
    }
    StringBuilder sb = new StringBuilder(len * 2 - 1);
    sb.append("?");
    for (int i = 1; i < len; i++) {
        sb.append(",?");
    }
    return sb.toString();
}</code>

This approach ensures that placeholders are replaced correctly and prevents SQL injection.

The above is the detailed content of How to Safely Use the IN Clause with Placeholders in SQLite for Android?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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