我是SQLITE
数据库的新手
我使用这些代码行来创建数据库,表和插入,检索数据
try {
SQLiteDatabase db = openOrCreateDatabase("Custom_Database", MODE_PRIVATE, null);
db.execSQL("Create Table If Not Exists Age (FirstName Varchar, LastName Varchar, age int(3));");
db.execSQL("Insert into Age Values ('Inzimam', 'Tariq', 22);");
Cursor c = db.rawQuery("Select * From Age", null);
c.moveToFirst();
Toast.makeText(getApplicationContext(), c.getString(c.getColumnIndex("pName")) + " " + c.getString(c.getColumnIndex("fName")), Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "Database Created Your code is working ! ", Toast.LENGTH_SHORT).show();
c.moveToNext();
db.close();
}catch (Exception e){
Toast.makeText(getApplicationContext(), "Error : " +e.getMessage(), Toast.LENGTH_LONG).show();
}
但是它会从
CursorWinsow
抛出异常而不是第0行,第-1列。 在访问数据之前,请确保光标已正确初始化 从它。
我认为c.moveToFirst();
应该为而做这个工作而不是为什么?
同样的代码在其他项目中是如何工作的。它在这个应用程序中给出错误的原因是什么?
编辑:在字符串中存储FisrtName和LastName并使用字符串Toast正常工作
String name = c.getString(0);
String father = c.getString(1);
Toast.makeText(getApplicationContext(), "Name = " + name + " " + father, Toast.LENGTH_SHORT).show();
但是我想知道通过Toast
或Strings
由于
答案 0 :(得分:0)
使用do =>尝试这种方式while:
if (c.moveToFirst()) { //looping through all rows
do {
Toast.makeText(getApplicationContext(), c.getString(c.getColumnIndex("pName")) + " " + c.getString(c.getColumnIndex("fName")), Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "Database Created Your code is working ! ", Toast.LENGTH_SHORT).show();
} while (c.moveToNext());
}
c.close();
db.close();
您还需要添加:
db = this.getWritableDatabase();
之前:
Cursor c = db.rawQuery("Select * From Age", null);