【问题标题】:Android SQLite custom queryAndroid SQLite 自定义查询
【发布时间】:2013-11-06 09:11:59
【问题描述】:

我有一个包含 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);

这是正确的吗?如果是,如何访问结果的每个元素?

【问题讨论】:

    标签: android database sqlite


    【解决方案1】:

    您的查询几乎是正确的。

    使用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}
    );
    

    要检查结果,请检查Cursor 方法。以下是一种可能的方法:

    for (c.moveToFirst(); c.isAfterLast() == false; c.moveToNext()) {
        some_variable=c.getString(0))
    }
    

    【讨论】:

    • 谢谢 LS_dev。它就像魅力一样!我使用了错误的 tableColumns 数据类型。没错,使用 rawQuery 更具可读性和简单性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-28
    • 1970-01-01
    • 2012-03-06
    • 2015-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多