Clausola IN e segnaposto


104

Sto tentando di eseguire la seguente query SQL su Android:

    String names = "'name1', 'name2";   // in the code this is dynamically generated

    String query = "SELECT * FROM table WHERE name IN (?)";
    Cursor cursor = mDb.rawQuery(query, new String[]{names});

Tuttavia, Android non sostituisce il punto interrogativo con i valori corretti. Potrei fare quanto segue, tuttavia, questo non protegge dall'iniezione SQL:

    String query = "SELECT * FROM table WHERE name IN (" + names + ")";
    Cursor cursor = mDb.rawQuery(query, null);

Come posso aggirare questo problema ed essere in grado di utilizzare la clausola IN?

Risposte:


188

Una stringa del modulo "?, ?, ..., ?"può essere una stringa creata dinamicamente e inserita in modo sicuro nella query SQL originale (perché è un modulo limitato che non contiene dati esterni) e quindi i segnaposto possono essere utilizzati normalmente.

Considera una funzione String makePlaceholders(int len)che restituisce punti leninterrogativi separati da virgole, quindi:

String[] names = { "name1", "name2" }; // do whatever is needed first
String query = "SELECT * FROM table"
    + " WHERE name IN (" + makePlaceholders(names.length) + ")";
Cursor cursor = mDb.rawQuery(query, names);

Assicurati solo di trasmettere esattamente tanti valori quanti sono i luoghi. Il limite massimo predefinito dei parametri host in SQLite è 999, almeno in una build normale, non sono sicuro di Android :)

Buona codifica.


Ecco un'implementazione:

String makePlaceholders(int len) {
    if (len < 1) {
        // It will lead to an invalid query anyway ..
        throw new RuntimeException("No placeholders");
    } else {
        StringBuilder sb = new StringBuilder(len * 2 - 1);
        sb.append("?");
        for (int i = 1; i < len; i++) {
            sb.append(",?");
        }
        return sb.toString();
    }
}

8
Sì, questo è (l'unico) modo per utilizzare query IN () con parametri in SQLite e praticamente qualsiasi altro database SQL.
Larry Lustig

Utilizzando questo metodo, ho aumentato il ContentProvider che ho utilizzato e nel metodo query () ho aggiunto la logica per verificare la presenza: "IN?" e se trovato, conta l'occorrenza di "?" nella selezione originale, rispetto alla lunghezza degli argomenti passati, assembla un "?,?, ...?" per la differenza e sostituisce l'originale "IN?" con la raccolta di punti interrogativi generata. Questo rende la logica disponibile quasi globale e per i miei usi sembra funzionare bene. Ho dovuto aggiungere alcune disposizioni speciali per filtrare gli elenchi IN vuoti, in quei casi, "IN?" è sostituito con "1" per ora.
SandWyrm

3
La cosa sciocca di questo è, ovviamente, che se hai intenzione di creare la tua stringa con N punti interrogativi, potresti anche codificare direttamente i dati. Supponendo che sia disinfettato.
Christopher,

16
Questo intero makePlaceholderspotrebbe essere sostituito con TextUtils.join(",", Collections.nCopies(len, "?")). Meno prolisso.
Konrad Morawski

1
Caused by: android.database.sqlite.SQLiteException: near ",": syntax error (code 1): , while compiling: SELECT url FROM tasks WHERE url=?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?
Iman Marashi

9

Breve esempio, basato sulla risposta dell'utente166390:

public Cursor selectRowsByCodes(String[] codes) {
    try {
        SQLiteDatabase db = getReadableDatabase();
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

        String[] sqlSelect = {COLUMN_NAME_ID, COLUMN_NAME_CODE, COLUMN_NAME_NAME, COLUMN_NAME_PURPOSE, COLUMN_NAME_STATUS};
        String sqlTables = "Enumbers";

        qb.setTables(sqlTables);

        Cursor c = qb.query(db, sqlSelect, COLUMN_NAME_CODE+" IN (" +
                        TextUtils.join(",", Collections.nCopies(codes.length, "?")) +
                        ")", codes,
                null, null, null); 
        c.moveToFirst();
        return c;
    } catch (Exception e) {
        Log.e(this.getClass().getCanonicalName(), e.getMessage() + e.getStackTrace().toString());
    }
    return null;
}

5

Purtroppo non c'è modo di farlo (ovviamente 'name1', 'name2' non è un valore singolo e quindi non può essere utilizzato in una dichiarazione preparata).

Quindi dovrai abbassare la vista (ad esempio creando query molto specifiche, non riutilizzabili come WHERE name IN (?, ?, ?)) o non utilizzare procedure memorizzate e cercare di prevenire le SQL injection con alcune altre tecniche ...


4
In realtà puoi, con un po 'di lavoro, creare una query IN parametrizzata. Vedi la risposta di pst, di seguito. La query risultante è parametrizzata e sicura per l'iniezione.
Larry Lustig

@ LarryLustig a quale risposta ti riferisci con la risposta "pst"? È stato cancellato? Questo sembra essere l'unico caso di pst qui ...
Stefan Haustein

1
@StefanHaustein " risposta di pst " (utente rimosso).
user4157124

5

Come suggerito nella risposta accettata ma senza utilizzare la funzione personalizzata per generare "?" Separati da virgole. Si prega di controllare il codice di seguito.

String[] names = { "name1", "name2" }; // do whatever is needed first
String query = "SELECT * FROM table"
    + " WHERE name IN (" + TextUtils.join(",", Collections.nCopies(names.length, "?"))  + ")";
Cursor cursor = mDb.rawQuery(query, names);

1

È possibile utilizzare TextUtils.join(",", parameters)per sfruttare i parametri di associazione sqlite, dove parametersè un elenco con "?"segnaposto e la stringa del risultato è qualcosa di simile"?,?,..,?" .

Ecco un piccolo esempio:

Set<Integer> positionsSet = membersListCursorAdapter.getCurrentCheckedPosition();
List<String> ids = new ArrayList<>();
List<String> parameters = new ArrayList<>();
for (Integer position : positionsSet) {
    ids.add(String.valueOf(membersListCursorAdapter.getItemId(position)));
    parameters.add("?");
}
getActivity().getContentResolver().delete(
    SharedUserTable.CONTENT_URI,
    SharedUserTable._ID + " in (" + TextUtils.join(",", parameters) + ")",
    ids.toArray(new String[ids.size()])
);

E se uno dei "parametri" deve essere nullo?
sviluppatore Android

0

In realtà potresti usare il modo nativo di query di Android invece di rawQuery:

public int updateContactsByServerIds(ArrayList<Integer> serverIds, final long groupId) {
    final int serverIdsCount = serverIds.size()-1; // 0 for one and only id, -1 if empty list
    final StringBuilder ids = new StringBuilder("");
    if (serverIdsCount>0) // ambiguous "if" but -1 leads to endless cycle
        for (int i = 0; i < serverIdsCount; i++)
            ids.append(String.valueOf(serverIds.get(i))).append(",");
    // add last (or one and only) id without comma
    ids.append(String.valueOf(serverIds.get(serverIdsCount))); //-1 throws exception
    // remove last comma
    Log.i(this,"whereIdsList: "+ids);
    final String whereClause = Tables.Contacts.USER_ID + " IN ("+ids+")";

    final ContentValues args = new ContentValues();
    args.put(Tables.Contacts.GROUP_ID, groupId);

    int numberOfRowsAffected = 0;
    SQLiteDatabase db = dbAdapter.getWritableDatabase());
        try {
            numberOfRowsAffected = db.update(Tables.Contacts.TABLE_NAME, args, whereClause, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        dbAdapter.closeWritableDB();


    Log.d(TAG, "updateContactsByServerIds() numberOfRowsAffected: " + numberOfRowsAffected);

    return numberOfRowsAffected;
}

0

Questo non è valido

String subQuery = "SELECT _id FROM tnl_partofspeech where part_of_speech = 'noun'";
Cursor cursor = SQLDataBase.rawQuery(
                "SELECT * FROM table_main where part_of_speech_id IN (" +
                        "?" +
                        ")",
                new String[]{subQuery}););

Questo è valido

String subQuery = "SELECT _id FROM tbl_partofspeech where part_of_speech = 'noun'";
Cursor cursor = SQLDataBase.rawQuery(
                "SELECT * FROM table_main where part_of_speech_id IN (" +
                        subQuery +
                        ")",
                null);

Utilizzando ContentResolver

String subQuery = "SELECT _id FROM tbl_partofspeech where part_of_speech = 'noun' ";

final String[] selectionArgs = new String[]{"1","2"};
final String selection = "_id IN ( ?,? )) AND part_of_speech_id IN (( " + subQuery + ") ";
SQLiteDatabase SQLDataBase = DataBaseManage.getReadableDatabase(this);

SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables("tableName");

Cursor cursor =  queryBuilder.query(SQLDataBase, null, selection, selectionArgs, null,
        null, null);

0

In Kotlin puoi usare joinToString

val query = "SELECT * FROM table WHERE name IN (${names.joinToString(separator = ",") { "?" }})"
val cursor = mDb.rawQuery(query, names.toTypedArray())

0

Uso l' StreamAPI per questo:

final String[] args = Stream.of("some","data","for","args").toArray(String[]::new);
final String placeholders = Stream.generate(() -> "?").limit(args.length).collect(Collectors.joining(","));
final String selection = String.format("SELECT * FROM table WHERE name IN(%s)", placeholders);

db.rawQuery(selection, args);
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.