简体   繁体   English

SQLite 仅返回第一行至 SELECT * 语句

[英]SQLite returns only first row through SELECT * Statement

I am saving some records in my sqlite table and records are being saved absolutely fine.我在我的sqlite表中保存了一些记录,并且记录保存得非常好。 Problem comes when I try to retrieve those records.当我尝试检索这些记录时,问题就来了。 Let's say I have 3 records in my sqlite so when I retrieve those records, it returns me the first record 3 times.假设我的 sqlite 中有 3 条记录,所以当我检索这些记录时,它会返回 3 次第一条记录。 Count is correct but why it returns me only first record 3 times?计数是正确的,但为什么它只返回我的第一条记录 3 次?

This is how I am retrieving the records:这就是我检索记录的方式:

public ArrayList<Cursor> getAllBookings() {
        ArrayList<Cursor> bookingsList = new ArrayList<>();
        SQLiteDatabase readableDatabase = this.getReadableDatabase();
        Cursor cursor = readableDatabase.rawQuery("SELECT * FROM " + BOOKING_TABLE, null);
        cursor.moveToFirst();
        for (int i = 0; i < cursor.getCount(); i++) {
            bookingsList.add(cursor);
            cursor.moveToNext();
        }

        return bookingsList;
    }

Please note that I have checked the table in Mozilla SQLiteManager and all records are successfully stored.请注意,我已在Mozilla SQLiteManager中检查了该table ,并且所有记录都已成功存储。

The problem is that you are adding the cursor itself to your booking list when you should extract and add the values that each cursor row contains.问题是当您应该提取并添加每个 cursor 行包含的值时,您正在将 cursor 本身添加到您的预订列表中。

So if you have a class Booking the method should be declared as因此,如果您有 class 预订,则该方法应声明为

public List<Booking> getAllBookings() {

Also I think it is better to have a do/while loop here and run it until cursor.moveToNext returns false and inside the loop extract all values using getString or similar methods另外我认为最好在这里有一个 do/while 循环并运行它直到cursor.moveToNext返回 false 并在循环内使用getString或类似方法提取所有值

List<Booking> bookingsList = new ArrayList<>();
//...
do {
    Booking booking = new Booking();
    booking.setSomething(cursor.getString("somethingColumn"));
    //... other columns
    bookingsList.add(booking);
} while (cursor.moveToNext());

If you don't have a custom class then you could use an array or a List for each row.如果您没有自定义 class 那么您可以为每一行使用一个数组或一个列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM