简体   繁体   中英

Java - SQLite - How to use the set of values for one column in where clause?

I want create query like this:

SELECT * FROM my_table WHERE column_1 in (1, 2, 3);

This query works in SQLite editor but I want to use it in Java. I try to use it like this:

String query = "SELECT * FROM mu_table WHERE coumn_1 in ?";
String[] args = {"(1, 2, 3)"};
Cursor c = db.rawQuery(query, args);

But this doesn't work. The following error occurs:

near "?": syntax error (code 1): , while compiling: SELECT * FROM my_table WHERE column_1 in ?

Why is it incorrect and what is correct way?

String query = "SELECT * FROM mu_table WHERE coumn_1 in (?, ?, ?)";
String[] args = new String[]{String.valueOf(1), String.valueOf(2), String.valueOf(3)};
Cursor c = db.rawQuery(query, args);

As it is required to pass selection argument compulsorily as string we can pass either as

String[]{String.valueOf(1), String.valueOf(2), String.valueOf(3)}

or as

String[]{"1", "2", "3"}

but it will compare as number only and not String. To make it compared as string we have to pass as

String[]{'1','2','3'}

but it is not required in current question context.

Parameters are used for single values that are not to be interpreted as SQL.

Furthermore, most functions in the Android database API allow only string parameters.

This query must be used directly:

db.rawQuery("SELECT ... IN (1, 2, 3)", null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM