gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:45:49 25 4
gpt4 key购买 nike

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

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

将数据插入数据库

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;
}

它应该显示输入的记录,但它使 toast“未找到记录”。

最佳答案

    Cursor cursor = database.rawQuery("select * from " + ChildMonitoringAppDBHelper.CHILD_TABLE_NAME, 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;

您可以尝试一下这段代码并看看它是否适合您吗?

关于java - 如何在 SQLite 中插入和检索数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55442545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com