swift - 使用 https ://cocoapods. org/pods/SQLite.swift 连接两个 sqlite 数据库时出现问题

标签 swift database sqlite execute sqlite.swift

我正在使用stephencelis/SQLite.swift并尝试在运行时附加 2 个数据库:

附加数据库\'(databasePath.Local)\' AS LOCAL_USER_DB;

//
//  DatabaseWrapper.swift
// ...
//

import UIKit
import SQLite

class DatabaseWrapper {

    // MARK: - Constants

    struct databaseName {
        static let Interface: String = "app_interface_sqlite3_db.db3"
        static let Local: String = "app_local_sqlite3_db_local.db3"
    }
    struct databasePath {
        static let path = NSSearchPathForDirectoriesInDomains(
            .documentDirectory, .userDomainMask, true
        ).first!
        static let Interface = "\(path)/\(databaseName.Interface)"
        static let Local = "\(path)//\(databaseName.Local)"
        static let Interface_Bundle: String = Bundle.main.path(forResource: "app_interface_sqlite3_db", ofType: "db3") ?? ""
        static let Local_Bundle: String = Bundle.main.path(forResource: "app_local_sqlite3_db_local", ofType: "db3") ?? ""
    }

    // MARK: Copy Databases

    public static func copyDatabasesIfNeeded() {
        copyDatabaseIfNeeded(databaseName: databaseName.Interface)
        copyDatabaseIfNeeded(databaseName: databaseName.Local)
    }

    public static func copyDatabaseIfNeeded(databaseName: String) {

        print("PATH: \(databasePath.Interface)")

        // Move database file from bundle to documents folder
        let fileManager = FileManager.default
        let documentsUrl = fileManager.urls(for: .documentDirectory,
                                            in: .userDomainMask)

        guard documentsUrl.count != 0 else {
            return // Could not find documents URL
        }

        let finalDatabaseURL = documentsUrl.first!.appendingPathComponent(databaseName)

        if !( (try? finalDatabaseURL.checkResourceIsReachable()) ?? false) {
            print("DB does not exist in documents folder")

            let documentsURL = Bundle.main.resourceURL?.appendingPathComponent(databaseName)

            do {
                try fileManager.copyItem(atPath: (documentsURL?.path)!, toPath: finalDatabaseURL.path)
            } catch let error as NSError {
                print("Couldn't copy file to final location! Error:\(error.description)")
            }

        } else {
            print("Database file found at path: \(finalDatabaseURL.path)")
        }
    }

    // MARK: - Attach Local User Database TESTS
    public static func attachDatabase() {

        do {
            // if the database connection works

            let db = try Connection(databasePath.Interface);

            let attachStr = "ATTACH DATABASE \'\(databasePath.Local)\' AS LOCAL_USER_DB;"

            try db.execute(attachStr)

        } catch {
            // handle error
            print("Unexpected error: \(error).")
        }

    }

    public static func checkIfDatabase2IsAttached() -> Bool {

        var isAllreadyAttached = false

        do {
            // if the database connection works

            let db = try Connection(databasePath.Interface);

            // seq, name, file
            var row_counter = 0
            for row in try db.prepare("PRAGMA database_list;") {
                print("\n\n----------\row: \(row)\n----------\n\n")
                row_counter += 1
            }
            isAllreadyAttached = (row_counter == 2) ? true : false

        } catch {
            // handle error
            print("Unexpected error: \(error).")
        }

        return isAllreadyAttached
    }

    public static func testIfDatabaseWasAttached() {

        do {
            // if the database connection works

            let db = try Connection(databasePath.Interface);

            for row in try db.prepare("SELECT * FROM LOCAL_USER_DB.users;") {
                print("row: \(row)")
            }

        } catch {
            // handle error
            print("Unexpected error: \(error).")
        }

    }

    // ...

}

当我打电话时

// Copy both databases if needed
        DatabaseWrapper.copyDatabasesIfNeeded()
        DatabaseWrapper.attachDatabase()

        if (DatabaseWrapper.checkIfDatabase2IsAttached()) {
            print("ATTACHED")
        } else {
            print("NOT ATTACHED YET")
        }

        DatabaseWrapper.testIfDatabaseWasAttached()

不幸的是,我无法工作,也没有收到任何错误消息。

在领事馆中我得到日志:

---------- ow: [Optional(0), Optional("main"), Optional("..../Developer/CoreSimulator/Devices/F93B5F0C-87D0-439C-ACB9-B1C6B5B7BE60/data/Containers/Data/Application/BB9587A1-2512-4003-ABC0-8AB1A7F6B4AF/Documents/app_interface_sqlite3_db.db3")]

NOT ATTACHED YET Unexpected error: no such table: LOCAL_USER_DB.users (code: 1).

有没有人知道,以前做过这个,或者有人帮助我吗?

提前致谢。

最佳答案

据我所知,该问题与 testIfDatabaseWasAttached() 有关。您确定您的表名称为 LOCAL_USER_DB.users 吗?您可以使用此代码 - 我已经检查并从表 LOCAL_USER_DB.users 中获取用户(该表的名称很奇怪,但没问题)。

public static func testIfDatabaseWasAttached() {
    do {

        let db = try Connection(databasePath.Interface);
        for element in try db.prepare(Table("LOCAL_USER_DB.users")) {
            print(element)
        }
    } catch {
        // handle error
        print("Unexpected error: \(error).")
    }
}

您应该确保您有名为 LOCAL_USER_DB.users 的表,并且错误说明了您的问题。数据库的这个结构: enter image description here

PS,当我运行你的代码时 - 在 [.documents] 中创建了 2 个数据库,但它们完全是空的(根本没有数据,只有两个数据库)。我建议检查流程逻辑

关于swift - 使用 https ://cocoapods. org/pods/SQLite.swift 连接两个 sqlite 数据库时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59823703/

相关文章:

java - 如何使用自定义 LIKE 参数创建数据库 View ?

mysql - 如何获取表 XYZ 的 ABC 数据库的数据库转储以及仅organization_id "22"的数据库转储?

python - SQLAlchemy 可以自动从数据库模式创建关系吗?

ios - 恢复核心数据

ios - 如何快速创建 3D 数组/矩阵?

mysql - 单个FK指来自多个表的PK

database - 没有绝对路径的Qt SQLite数据库

python - 我的 flask sqlite 数据库中的图像应该使用什么数据类型?

swift - Swift 中的嵌套类型 - 好的做法是什么?

objective-c - respondsToSelector 的 Swift 等价物是什么?