我有一个包含5列的数据库,名为col_1,col_2,col_3,col_4,col_5 所有这些列都是TEXT类型。 比如,表的名称是my_table,我在数据库表中有10个条目
col_1 col_2 col_3 col_4 col_5
001 01 001 John1 Wright1
002 02 002 John2 Wright2
001 02 003 John3 Wright3
003 01 004 John4 Wright4
001 01 005 John5 Wright5
004 01 006 John6 Wright6
001 03 007 John7 Wright7
002 01 008 John8 Wright8
002 02 009 John9 Wright9
005 01 010 John0 Wright0
我想根据col_1和col_2的值编写一个函数来查询此数据库,并将col_4(值数组)的所有可能值放入列表中。
说,我想查询col_1 =“001”AND col_2 =“01”,我希望结果是一个包含{John1,John5}的字符串数组
String [] tableColumns = new String[1];
tableColumns = "col_4";
String whereClause = "col_1=? AND col_2=?";
String [] whereArgs = {col_1_val, col2_val}; //where col_1_val = "001" and col_2_val = "01"
Cursor c = qb.query(db, tableColumns, whereClause , whereArgs , null, null, null, null);
这是对的吗?如果是这样,如何访问结果的每个元素?
答案 0 :(得分:0)
您的查询几乎是正确的。
使用SQLiteDatabase的文档,您应该使用:
String [] tableColumns = {"col_4"};
String whereClause = "col_1=? AND col_2=?";
String [] whereArgs = {col_1_val, col2_val}; //where col_1_val = "001" and col_2_val = "01"
Cursor c = query(
true, //boolean distinct
"my_table", //String table
tableColumns,//String[] columns
whereClause, //String selection
whereArgs, //String[] selectionArgs
null, //String groupBy
null, //String having
null, //String orderBy
null, //String limit
null //CancellationSignal cancellationSignal
);
我,我自己,更喜欢使用rawQuery
:
Cursor c = db.rawQuery(
"SELECT DISTINCT col_4 FROM my_table WHERE col_1=? AND col_2=?",
new String[] {col_1_val, col2_val}
);
对于fecthing结果,请检查Cursor方法。以下是一种可能的方法:
for (c.moveToFirst(); c.isAfterLast() == false; c.moveToNext()) {
some_variable=c.getString(0))
}