为什么在此指令中存在运行时错误

时间:2013-02-08 00:38:06

标签: android

SQLiteDatabase db = this.openOrCreateDatabase("students", MODE_PRIVATE, null);

/* db.execSQL("create table info (" +
    "id integer PRIMARY KEY autoincrement," +
    "name text);" );*/

//   db.execSQL("insert into info (name) values ('Ahmed');");

//   db.execSQL("insert into info (name) values ('Ali');");

Toast.makeText(this, "databse done and informations inserted succesfully", Toast.LENGTH_LONG).show();

Cursor c1 = db.rawQuery("select * from info where name = 'ahmed';", null);

//this line gives runtime error
String x = c1.getString(c1.getColumnIndex("name"));

Toast.makeText(this, x, Toast.LENGTH_LONG).show();

1 个答案:

答案 0 :(得分:0)

在行

之前添加c1.moveToFirst();
String x = c1.getString(c1.getColumnIndex("name"));

另外,请考虑使用getColumnIndexOrThrow代替getColumnIndex来确保您指定了正确的列名称(否则您将获得例外)

一般情况下,最好使用query代替rawQuery,尤其是在您执行简单查询的示例中