Home >Database >Mysql Tutorial >How to Safely Use the IN Clause with Placeholders in SQLite for Android?
SQLite queries using IN clauses with dynamic string concatenation in Android face the following challenges:
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!