从表中获取一行

时间:2012-09-18 08:35:21

标签: android-sqlite

这些是我表中的ID:

KEY_ID(autoincremented integer primary key)   KEY_NAME(text)     KEY_PH_NO(text)

1                                             james                   1234567890
2                                             kristein                6484996755
3                                             Roen                    4668798989
4                                             Ashlie                  6897980909

我想知道的是,如何在unique(KEY_ID)的基础上从此表中获取单个记录,因为我已经构建了这样的getContact()方法,

Contact getContact(int id) {
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
            KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
            new String[] { String.valueOf(id) }, null, null, null, null);
    if (cursor != null)
        cursor.moveToFirst();

    Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
            cursor.getString(1), cursor.getString(2));
    // return contact
    return contact;
}

Contact是一个我为所有属性设置了所有getter和setter方法的类。

请提供完整的代码帮助。

3 个答案:

答案 0 :(得分:37)

看看这是否可以帮助你..

假设您的表名是Employee

public String getEmployeeName(String empNo) {
    Cursor cursor = null;
    String empName = "";
    try {
        cursor = SQLiteDatabaseInstance_.rawQuery("SELECT EmployeeName FROM Employee WHERE EmpNo=?", new String[] {empNo + ""});
        if(cursor.getCount() > 0) {
            cursor.moveToFirst();
            empName = cursor.getString(cursor.getColumnIndex("EmployeeName"));
        }
        return empName;
    }finally {
        cursor.close();
    }
}

答案 1 :(得分:10)

Contact getContact(int id) {
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
        KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
        new String[] { String.valueOf(id) }, null, null, null, null);
    if (cursor != null)
        cursor.moveToFirst();

    Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
                        cursor.getString(1), cursor.getString(2));
    // return contact
    return contact;
}

假设您有联系的实体类,那么您只需将其称为上面的方法。

Contact singleContact = database.getContact(id);

然后调用联系人实体,我假设你有方法getter getPhone();

Log.d("Phone Number :" , singleContact.getPhone());

答案 2 :(得分:0)

试试这个

cursor.moveToPosition(position); cursor.getString(listaTarefas1.getColumnIndex("Item"))