如何在Swift中获取SQLite3查询中的行数

时间:2018-02-06 17:22:39

标签: sql swift sqlite

cmd sqlite3_column_count(statement)在Swift中的SQLite3查询中运行良好。

但是,我想获得查询的行数(而不是列数)。适合的cmd是什么? (即sqlite3_row_count似乎不存在)。

任何想法都赞赏!

这是我的代码:

    // Open SQLite database
    var db: OpaquePointer? = nil
    if sqlite3_open(self.fileURL, &db) == SQLITE_OK {

        // Run SELECT query from db
        var statement: OpaquePointer? = nil
        if sqlite3_prepare_v2(db, query, -1, &statement, nil) == SQLITE_OK {

            // Loop through all results from query
            var stop_id_memory = ""

            // !!!!!!!! works well !!!!!!!!!!!!!
            print(sqlite3_column_count(statement))

            // !!!!!!!! does not work well !!!!!!!!!!!!!
            print(sqlite3_row_count(statement))

            while sqlite3_step(statement) == SQLITE_ROW {
               let id = sqlite3_column_text(statement, 0)
               // do whatever with the id ....
               // ...
            }
        }
    }

1 个答案:

答案 0 :(得分:-1)

这是一个解决方案,里面的计数器......

var query1: String = ".....my first query....."
var query2: String = ".....my second query...."
var i = 0
var usedQuery = ""

// Open SQLite database
var db: OpaquePointer? = nil
if sqlite3_open(self.fileURL, &db) == SQLITE_OK {

    // Run SELECT query from db
    var statement: OpaquePointer? = nil
    if sqlite3_prepare_v2(db, query1, -1, &statement, nil) == SQLITE_OK {

        // Loop through all results from query
        while sqlite3_step(statement) == SQLITE_ROW {
            i = i + 1
        }
    }
    if (i < 5 ) {
        usedQuery = query2
    } else {
        usedQuery = query1
    }
    statement = nil
    if sqlite3_prepare_v2(db, usedQuery, -1, &statement, nil) == SQLITE_OK {

        // Loop through all results from query
        var stop_id_memory = ""
        while sqlite3_step(statement) == SQLITE_ROW {
            let id = sqlite3_column_text(statement, 0)
            // do whatever with the id ....
            // ...
        }  
    }
}