android sqlite数据库游标

时间:2012-08-10 11:14:50

标签: android database sqlite

我有一个android应用程序,它在资产文件夹中有一个小数据库作为db文件。该文件名为nametoareamap.db。它有一个名为'map'的表。该表有两列(名称和区域)如下:

Names       Areas

Aaron        A

Chris        A 

Helen        B 

Tim          B

我的应用程序将名称作为用户的输入。假设一些用户有输入:Aaron,Tim。 在这种情况下,就名称而言,与数据库存在两个匹配。但他们来自不同的领域。来自A的Aaron和来自B.的Tim。我想实现以下逻辑。

If match > = 2 && the area of the matches are same

{ i take a decision}

else

 {i decide something else }

任何人都可以在Android上向我提供使用游标和sqlite数据库执行此操作所需的代码。我已经有了数据库适配器。提前谢谢

1 个答案:

答案 0 :(得分:1)

假设以下表格布局

CREATE TABLE name_area (
    _id INTEGER PRIMARY KEY NOT NULL,
    name TEXT NOT NULL,
    area TEXT NOT NULL,
    UNIQUE(name, area)
)

以下值

name      area
----      ----
Aaron     A
Chris     A
Bunny     A
Ron       A
Burgundy  B
Helen     B 
Tim       B

假设您想知道Aaron,Ron和Burgundy是否都在同一地区:

SELECT COUNT(*), area FROM name_area 
    WHERE name='Aaron' OR name='Ron' OR name='Burgundy' GROUP BY area

这将返回两行。

2   A
1   B

即。其中两个在同一区域(A),一个在另一个区域(B):

Cursor表示,您可以这样检查:

Cursor cursor = ...; // Format your query & do the SELECT
try {
    if (cursor.moveToNext()) {
        int count = cursor.getCount();
        if (count < 2) {
            // Everyone is in the same area
            int n = cursor.getInt(0);
            // Now verify 'n' against the number of people you queried for
            // if it doesn't match one or more didn't exist in your table.
        } else {
            // People are in different areas
            int n = 0;
            do {
               n += cursor.getInt(0);
            } while (cursor.moveToNext());
            // Now verify 'n' against the number of people you queried for
            // if it doesn't match one or more didn't exist in your table.
        }
    } else {
        // Oops nothing was found.
    }
} finally {
    cursor.close();
}