0

How can I check the last row in this loop below. Im using SQlite.swift in order to cycle through all the rows in the table. When I hit the last row, I want to do something.

    for data in try dbConnection.prepare(tableName) {
        if (thisIsTheLastRow) {
          //do something
         }
}

Here is the library reference but I couldent find anything about getting specific indexes through the loop

Nikola
  • 371
  • 1
  • 9
  • 19
plgelso
  • 107
  • 2
  • 15

2 Answers2

0

You could either do a for index loop:

let count = try! db.scalar("SELECT count(*) FROM Table") as! Int64
for (index, data) in stmt.enumerated() {
    if index == Int(count)  {
        // Last row

    }
}

Or you could in that library make an sqlite statement and get the last row immediately:

func lastRowForTable() -> Data {
   let data = try! db.scalar("SELECT * FROM table ORDER BY column DESC LIMIT 1;")
   return data
}
Rashwan L
  • 38,237
  • 7
  • 103
  • 107
  • The for index loop is what I need to use because Im doing other things in the loop when its not the last row. I really appreciate your help. When I punch in the first loop I get a an error in Xcode "value of type 'EnumeratedSequence>' has no member 'count' " @Rashwan L. – plgelso May 25 '17 at 13:28
  • @plgelso, check the updated example for the index iteration. – Rashwan L May 25 '17 at 13:39
  • Make sure to wrap all your statements in a transaction, or another thread may modify the database in between. – Gwendal Roué May 26 '17 at 06:43
0

SQLite computes result rows on demand. So there is no way to find out whether the current row is the last one except by trying to stepping to the next one.

You have to load all rows before looping over them, or do the "do something" after the loop.

CL.
  • 173,858
  • 17
  • 217
  • 259