Android Sqlite IN,NOT IN语法

我试图运行NOT IN select NOT IN列表是dynamic的。 就像是

 SELECT id, type FROM CONTACTS where type NOT IN ('connect','answer') 

在代码中,我徒劳的尝试是:

 db.query(TABLE, new String[] { "id", ""}, " type NOT IN (?)", "connect,answer", null, null, null); // didn't work db.query(TABLE, new String[] { "id", ""}, " type NOT IN (?)", "'connect','answer'", null, null, null); // didn't work 

我承认这是? 替代品将我的逗号列表视为单一的参数。 我find了一个解决scheme,但是相当丑陋,所以我不会在这里发布,直到有人提出更优雅的东西

Solutions Collecting From Web of "Android Sqlite IN,NOT IN语法"

你不能放一个'?' 而不是一个值列表。 因此,尝试参数化列表几乎没有什么收获。 当然,可以创build2,4,16个值的准备语句..." type NOT IN (?,?)", new String[]{ "connect","answer" },...但是甚至在具有远程RDBMS的服务器具有可疑价值。 相反,做

 db.query(TABLE, new String[] { "id", ""}, " type NOT IN ('connect','answer')", null, null, null, null); 

如果列表是dynamic的,则必须将string转义并放入单引号列表中。

您可以使用String.formatdynamic设置参数。

例如:

 db.query(TABLE, new String[] { "id", ""}, " type NOT IN (?)", "connect,answer", null, null, null); 

=>

 String argsArrayToString(List<String> args) { StringBuilder argsBuilder = new StringBuilder(); argsBuilder.append("("); final int argsCount = args.size(); for (int i=0; i<argsCount; i++) { argsBuilder.append(args.get(i)); if (i < argsCount - 1) { argsBuilder.append(","); } } argsBuilder.append(")"); } db.query(TABLE, new String[] { "id", ""}, String.format(" type NOT IN (%s)", argsArrayToString(arrays)), null, null, null, null); 

如果你dynamic地创build一个包含“不在”值的列表的string,然后将它们附加到你的sqlstring的末尾,你可以dynamic地使用它“not in”

 public static Vector selectAllFormTypesForAccountIgnoringFormVersions( int accountId, String formsIgnored) { protected final static String selectAllFormTypesForAccountIgnoringFormVersions = "SELECT DISTINCT FormType.*" + " FROM FormType, Form WHERE Form.accountId=? AND FormType.formTypeContentId = Form.formTypeContentId" + " AND Form.formVersionId NOT IN ("; Vector allFormTypes = new Vector(); SQLiteDatabase db = null; String[] selectionArgs = { Integer.toString(accountId)}; try { DataManager_Platform dataManager = (DataManager_Platform) DataManager_Platform .getDataManager(); db = (SQLiteDatabase) dataManager.getDatabase(); Cursor cursor = db.rawQuery( selectAllFormTypesForAccountIgnoringFormVersions + formsIgnored + ")", selectionArgs); if (cursor.getCount() > 0) { cursor.moveToFirst(); while (!cursor.isAfterLast()) { FormType_Platform formType = new FormType_Platform(); formType.populateModel(cursor); allFormTypes.add(formType); cursor.moveToNext(); } } } catch (Exception e) { System.out.println("Error: " + e.getMessage()); e.printStackTrace(); } finally { try { if (db != null) { db.close(); } } catch (Exception e) { System.out.println("Error: " + e.getMessage()); e.printStackTrace(); } } return allFormTypes; }