尝试将记录添加到sqlite Swift时发现nil

时间:2017-06-18 01:02:11

标签: ios swift sqlite

我使用以下内容创建表:

  let db = try Connection("\(path)/db.sqlite3")   

        let users = Table("users")
        let assetTag = Expression<String?>("asset_tag")
        let location = Expression<String?>("location")


        try db.run(users.create { t in
            t.column(assetTag)
            t.column(location)

然后我使用以下内容向两列添加记录:

 for tag in tags

        {
            try db.run(users.insert(assetTag <- tag))

        }

        for locale in locations
        {
            try db.run(users.insert(location <- locale))

        }

然后我选择值并尝试使用它打印:

 for user in try db.prepare(users.select(assetTag)) {
                    tagArray.append(user[assetTag])
            }

            for user in try db.prepare(users.select(location)) {
                locationArray.append(user[location])
            }

            print (tagArray)
            print (locationArray)

出于某种原因,我收到一个错误,说明某处有一个零值,但我不确定零来自哪里。另请注意,我删除了catch语句以便于阅读。

1 个答案:

答案 0 :(得分:0)

经过一些研究后,我发现有两个插入语句没有正确插入我的记录并插入空值。下面的代码是如何将两个数组同时插入数据库以防止空值:

for (locale, tag) in zip(locations, tags)

        {
            try db.run(users.insert(assetTag <- tag, location <- locale))

        }