Select 获取字段时的查询问题
Select Query issue while fetching the fields
我写了一个查询,其中 select 基于 id 的名称和指定字段,然后在片段 class 我正在调用属于适当查询的方法,但不幸的是我得到了 Sqlite 异常.
数据库方法
public Employee getEmployeeName(int id) {
SQLiteDatabase db = this.getWritableDatabase();
Employee employee = new Employee();
String query ="SELECT " + KEY_NAME +", " +KEY_DESIG +" FROM " + TABLE_EMPLOYEES+ " WHERE " + KEY_ID + "=" + id;
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
employee.setName(cursor.getString(1));
employee.setDesignation(cursor.getString(2));
} while (cursor.moveToNext());
}
return employee;
}
从片段调用
db.getEmployeeName(selectedManager);
异常
01-07 06:02:34.185: E/AndroidRuntime(2386): java.lang.IllegalStateException: Couldn't read row 0, col 2 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
试试这个
if (cursor.moveToFirst()) {
do {
employee.setName(cursor.getString(cursor.getColumnIndex(KEY_NAME));
employee.setDesignation(cursor.getString(cursor.getColumnIndex(KEY_DESIG));
} while (cursor.moveToNext());
}
使用 cursor.getColumnIndex(COLUMN NAME)
从 Cursor
获取数据
列索引是从零开始的。 getString(2)
指的是第三列,而您的光标只有两列。
改变
employee.setName(cursor.getString(1));
employee.setDesignation(cursor.getString(2));
至
employee.setName(cursor.getString(0));
employee.setDesignation(cursor.getString(1));
我写了一个查询,其中 select 基于 id 的名称和指定字段,然后在片段 class 我正在调用属于适当查询的方法,但不幸的是我得到了 Sqlite 异常.
数据库方法
public Employee getEmployeeName(int id) {
SQLiteDatabase db = this.getWritableDatabase();
Employee employee = new Employee();
String query ="SELECT " + KEY_NAME +", " +KEY_DESIG +" FROM " + TABLE_EMPLOYEES+ " WHERE " + KEY_ID + "=" + id;
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
employee.setName(cursor.getString(1));
employee.setDesignation(cursor.getString(2));
} while (cursor.moveToNext());
}
return employee;
}
从片段调用
db.getEmployeeName(selectedManager);
异常
01-07 06:02:34.185: E/AndroidRuntime(2386): java.lang.IllegalStateException: Couldn't read row 0, col 2 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
试试这个
if (cursor.moveToFirst()) {
do {
employee.setName(cursor.getString(cursor.getColumnIndex(KEY_NAME));
employee.setDesignation(cursor.getString(cursor.getColumnIndex(KEY_DESIG));
} while (cursor.moveToNext());
}
使用 cursor.getColumnIndex(COLUMN NAME)
Cursor
获取数据
列索引是从零开始的。 getString(2)
指的是第三列,而您的光标只有两列。
改变
employee.setName(cursor.getString(1));
employee.setDesignation(cursor.getString(2));
至
employee.setName(cursor.getString(0));
employee.setDesignation(cursor.getString(1));