.prepare vs. .select

时间:2016-12-11 00:28:36

标签: swift sqlite

我使用SQLite.swift与iOS10应用程序中的数据库建立了连接。

我想选择一个特定大学的详细信息,我从另一个视图控制器传入IHE_ID。

我想只选择该特定大学的行,但我无法获得查询。然而,我可以使用prepare循环遍历所有数据,然后从中选择我需要的数据,这当然比我需要的资源更密集,因为我已经从发送视图控制器传入了作为anIHE Int的特定IHE_ID。 / p>

连接正在工作,省略了代码...

 do {
                        let db = try Connection(destinationDBPath, readonly: true)
                        let IHEs = Table("IHE")
                        let IHE_ID = Expression<Int>("IHE_ID")
                        let IHE_Name = Expression<String>("IHE_Name")
                        let IHE_COE_Url = Expression<String>("IHE_COE_URL")
                        let IHE_Sector = Expression<Int>("IHE_Sector")
                        let IHE_COE_Name = Expression<String>("IHE_COE_Name")
        for ihe in try db.prepare(IHEs){
                        if (ihe[IHE_ID] == anIHE){

                            // build this string, otherwise ignore rest of dataset (doing this because query isn't working)

                            buildIHE = "Name: \(ihe[IHE_Name])\n"
                            buildIHE.append("URL: \(ihe[IHE_COE_Url])\n")
                            // buildIHE.append("Sector: \(ihe[IHE_Sector])\n")

                            if (ihe[IHE_Sector] == 0) {
                                buildIHE.append("Sector: Public\n")
                            } else {
                                buildIHE.append("Sector: Private\n")
                            }
                            buildIHE.append("College of Education Name: \(ihe[IHE_COE_Name])\n")

                        }

                    }
                    print ("Got through building IHE portion of view")

我想做的是使用它而不是for循环。

    if let query = IHEs.select(IHE_ID,IHE_Name,IHE_COE_Url,IHE_Sector,IHE_COE_Name).filter(IHE_ID == anIHE){
                print("Query successful for \(anIHE) with name \(query[IHE_Name])")
            // more actions to build the string I need would then occur
            } else {
                print("Query has failed or returned nil")
            }

最后,如果我可以使查询起作用,我将使用所选元素。 我想我的查询语法可能有问题,但是感谢任何帮助。

带有“if let query”的行在Xcode中出现此错误: 条件绑定的初始化程序必须具有可选类型,而不是“表”。 这让我认为这是我使用.select语句的一些东西,而且只是使用SQLite.swift和swift的新东西。

最后一点是anIHE作为Int进入此函数,IHE_ID是Expression,如此代码所示。我认为这可能是问题的一部分。

1 个答案:

答案 0 :(得分:0)

Initializer for conditional binding must have Optional type错误意味着if let v = expr语句右侧的表达式不是可选的:使用if是没有意义的,Swift编译器说你应该只写{{ 1}}。

事实上,let v = expr会返回类型为IHEs.select(...).filter(...)的非可选值。

它不是您期望的数据库行,因为查询已已定义,但尚未已执行。毕竟,你没有使用Table:从哪里加载行?

解决方案是恢复数据库连接,并加载一行。这是通过pluck方法完成的。

db
相关问题