user10318011
user10318011

Reputation:

Swift SQLite how to get row.count from table?

in my Xcode Project, I use SQLite to save user order list

My question is if my data like this enter image description here

Is there any way like table.count and I can get how many row it is ?

Here's my insert method I hope it can be like this

just create a model, and use directly

func insert(_ tableName :String, rowInfo :[String:String]) -> Bool {
    var statement :OpaquePointer? = nil
    let sql = "insert into \(tableName) "
        + "(\(rowInfo.keys.joined(separator: ","))) "
        + "values (\(rowInfo.values.joined(separator: ",")))"

    if sqlite3_prepare_v2(self.db, sql.cString(using: String.Encoding.utf8), -1, &statement, nil) == SQLITE_OK {
        if sqlite3_step(statement) == SQLITE_DONE {
            return true
        }
        sqlite3_finalize(statement)
    }

    return false
} 

Upvotes: 1

Views: 4117

Answers (2)

Saleh Enam Shohag
Saleh Enam Shohag

Reputation: 1119

let query = "select count(*) from tableName;"
if sqlite3_prepare(self.db, query, -1, &queryStatement, nil) == SQLITE_OK{
      while(sqlite3_step(queryStatement) == SQLITE_ROW){
           let count = sqlite3_column_int(queryStatement, 0)
           print("\(count)")
      }

}

Above code will give you the row count of the table.

Upvotes: 4

Alex
Alex

Reputation: 1245

If you are using pure SQLite, you must use SQL requests to get any info from your database. In your case the request will be like this one:

"SELECT COUNT(*) FROM \(tableName)"

But why don't you use CoreData? It has not only a lot of necessary methods to make your data access easier, but also tons of optimisation code for both speed and memory using (what is much more important in my eyes).

Upvotes: 0

Related Questions