通过Swift中的SQLClient从SQL Server中提取数据

问题描述 投票:0回答:1

我试图从SQL Server中提取数据,但我无法存储数据。我得到的所有行都在“外部”,我的数据为零。这意味着在我断开数据库之前我有数据,但是当我关闭连接时,所有数据都消失了。

我想这是因为我有浅拷贝,我需要深度复制

import Foundation
import SQLClient

class RecipeViewModel{
var recipes = [Recipe]()

init(){
    getRecipeFromDB()
}

func getRecipeFromDB(){

    let client = SQLClient.sharedInstance() as! SQLClient

    client.connect("x.x.x.x", username: "xx", password: "xxx", database: "xxx") {
        success in
        client.execute("SELECT item FROM TABLE") {
            results in

            for table in results as! [[[String:AnyObject]]] {
                for row in table {

                    for (columnName, value) in row {
                        let recipe = Recipe(code: value as! String, title: "Title")
                        recipes.append(recipe)
                        }
                    }
                }
// prints all recipes. Everything is perfect

        for i in self.recipes{
            print(i.code)
        }
            client.disconnect()
        }
//prints nothing. recipe.count = 0

        for i in self.recipes{
            print(i.code)
        }
    }
}

func error(error: String!, code: Int32, severity: Int32) {
    print(error)
    }
}
sql sql-server swift sqlclient
1个回答
1
投票

我认为这是因为您在关闭后立即执行打印配方。由于函数中的闭包不是按顺序运行的,所以在带闭包的函数之后不应该立即读取数据(不能保证在外部函数下面的下一个语句之前执行闭包)。您必须使用completion闭包来存档您的目标。

func getRecipeFromDB(completion: ([Recipe]) -> Void){

    let client = SQLClient.sharedInstance() as! SQLClient

    client.connect("x.x.x.x", username: "xx", password: "xxx", database: "xxx") {
        success in
        client.execute("SELECT item FROM TABLE") {
            results in

            for table in results as! [[[String:AnyObject]]] {
                for row in table {

                    for (columnName, value) in row {
                        let recipe = Recipe(code: value as! String, title: "Title")
                        recipes.append(recipe)
                    }
                }
            }
            // prints all recipes. Everything is perfect

            for i in self.recipes{
                print(i.code)
            }
            client.disconnect()

            // This is important to invoke the callback when reading data is done
            completion(self.recipes)
        }
    }
}

// Call your query data with a completion
getRecipeFromDB {
    (data) in
    for i in data{
        print(i.code)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.