使用swift的SQLite,我无法从我的表查询中获取所有元素

时间:2016-05-24 08:24:09

标签: xcode swift sqlite

我是swift和SQLLite的新手,我遇到了问题,我不知道如何修复它

我创建的表包含[id name Grade],这是我的插入函数

let insertStatementString = "INSERT INTO Contact (Id, Name, Grade ) VALUES (?, ?, ?);"

func insert() {
    var insertStatement: COpaquePointer = nil

    // 1
    if sqlite3_prepare_v2(db, insertStatementString, -1, &insertStatement, nil) == SQLITE_OK {

        let dic: [NSString] = ["Ray", "Chris", "Martha", "Danielle"]
        let grade = [11 , 13 ,11 ,12]
        var id = Int32()
        for (index, name) in dic.enumerate() {
            sqlite3_bind_int(insertStatement, 1, index + 1)
            sqlite3_bind_text(insertStatement, 2, name.UTF8String, -1, nil)
            sqlite3_bind_int(insertStatement, 3,Int32(grade[index]))
            id = id + 1

        }
        if sqlite3_step(insertStatement) == SQLITE_DONE {
            print("Successfully inserted row.")
        } else {
            print("Could not insert row.")
        }
    } else {
        print("INSERT statement could not be prepared.")
    }
    // 5
    sqlite3_finalize(insertStatement)
}

   insert()

当我调用我的查询函数时,while循环只工作一次,但是你可以看到我的表中有4个元素

这是我的查询功能

let queryStatementString = "SELECT * FROM Contact;"
func query() {
    var queryStatement: COpaquePointer = nil
    if sqlite3_prepare_v2(db, queryStatementString, -1, &queryStatement, nil) == SQLITE_OK {
        while (sqlite3_step(queryStatement) == SQLITE_ROW) {
            let id = sqlite3_column_int(queryStatement, 0)
            let queryResultCol1 = sqlite3_column_text(queryStatement, 1)
            let grade =  sqlite3_column_int(queryStatement, 2)
            let name = String.fromCString(UnsafePointer<CChar>(queryResultCol1))!
            print("Query Result:")
            print("\(id) | \(name) | \(grade)")
        }

    } else {
        print("SELECT statement could not be prepared")
    }

    sqlite3_finalize(queryStatement)
} 
query()

最后一件事,这是我的创建表函数

let db = openDatabase()
let createTableString = "CREATE TABLE Contact(" + "Id INT PRIMARY KEY NOT NULL," + "Name CHAR(255)," + "Grade INTEGER)"

func createTable() {

    var createTableStatement: COpaquePointer = nil

    if sqlite3_prepare_v2(db, createTableString, -1, &createTableStatement, nil) == SQLITE_OK {

        if sqlite3_step(createTableStatement) == SQLITE_DONE {
            print("Contact table created.")
        } else {
            print("Contact table could not be created.")
        }
    } else {
        print("CREATE TABLE statement could not be prepared.")
    }

    sqlite3_finalize(createTableStatement)
}


createTable()

1 个答案:

答案 0 :(得分:2)

在insert()函数中,调用sqlite3_step()一次。这就是您插入一行的原因。将调用移至循环内的sqlite3_step()名称和等级。在设置绑定之前还要调用sqlite3_reset()。