如何在SQLite中插入和检索数据?

时间:2019-03-31 15:38:07

标签: java android android-sqlite

我编写了一个应用程序,其中我必须将其数据插入sqlite数据库并在一项活动中显示它。但是我的代码显示“没有找到记录”,即使我已将其插入。

我尝试使用不同的选项,例如先将光标移动到第一条记录,然后使用循环遍历该记录。

将数据插入数据库

private void saveToDB() {
        SQLiteDatabase database = new ChildMonitoringAppDBHelper(this).getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(ChildMonitoringAppDBHelper.CHILD_NAME, name.getText().toString());
        values.put(ChildMonitoringAppDBHelper.CHILD_AGE, age.getText().toString());
        values.put(ChildMonitoringAppDBHelper.CHILD_DOB, dob.getText().toString());
        values.put(ChildMonitoringAppDBHelper.CHILD_HEIGHT, height.getText().toString());
        values.put(ChildMonitoringAppDBHelper.CHILD_WEIGHT, weight.getText().toString());
        database.insert(ChildMonitoringAppDBHelper.CHILD_TABLE_NAME, null, values);
        database.close();   
    }

从数据库检索数据

public ArrayList<Child> readFromDB()
    {
        ArrayList<Child> List = new ArrayList<>();
        SQLiteDatabase database = new ChildMonitoringAppDBHelper(this).getReadableDatabase();
        Cursor cursor = database.rawQuery("select * from " + ChildMonitoringAppDBHelper.CHILD_TABLE_NAME, null);
        cursor.moveToFirst();
        while(!cursor.isAfterLast())
        {
            Child child = new Child(cursor.getString(cursor.getColumnIndex("CHILD_NAME")), cursor.getString(cursor.getColumnIndex("CHILD_AGE")), cursor.getString(cursor.getColumnIndex("CHILD_DOB")), cursor.getString(cursor.getColumnIndex("CHILD_HEIGHT")), cursor.getString(cursor.getColumnIndex("CHILD_WEIGHT")));
            List.add(child);
            cursor.moveToNext();
        }
        cursor.close();
        return List;
    }

它应该显示输入的记录,但它在吐司“找不到记录”。

2 个答案:

答案 0 :(得分:0)

}

您能尝试一下此代码并查看它是否适合您吗?

答案 1 :(得分:0)

  public ArrayList<Child> readFromDB() 
   {
  List list = new ArrayList<Child>(); 
  Cursor cursor = database.rawQuery("select * from " + 
  ChildMonitoringAppDBHelper.CHILD_TABLE_NAME, null);
  SQLiteDatabase database = this.getWritableDatabase(); 
  Cursor cursor = database.rawQuery(selectQuery, null); 
  if (cursor.moveToFirst())
  {  
  do
  {
 Child child = new Child(cursor.getString(cursor.getColumnIndex("CHILD_NAME")), 
 cursor.getString(cursor.getColumnIndex("CHILD_AGE")), 
 cursor.getString(cursor.getColumnIndex("CHILD_DOB")), 
 cursor.getString(cursor.getColumnIndex("CHILD_HEIGHT")), 
 cursor.getString(cursor.getColumnIndex("CHILD_WEIGHT")));

 list.add(child);
 } 
 while (cursor.moveToNext());
 }
cursor.close(); 
// return list of inserted values
return list; 
}