代码之家  ›  专栏  ›  技术社区  ›  Rutger Huijsmans

使用Vapor框架建立数据库连接

  •  2
  • Rutger Huijsmans  · 技术社区  · 6 年前

    我已经创建了一个SQLite数据库,并且能够使用DB客户机连接到它。

    现在我希望我的Swift Vapor项目也使用FluentSQLite包连接到它。

    我已在项目的根文件夹中创建了数据库:

    /Users/rutgerhuijsmans/Documents/runk-3.0

    我的数据库叫做 runk-3.0-database

    文件夹如下所示:

    enter image description here

    我尝试使用以下配置连接到数据库:

    import FluentSQLite
    import Vapor
    
    /// Called before your application initializes.
    public func configure(_ config: inout Config, _ env: inout Environment, _ services: inout Services) throws {
        /// Register providers first
        try services.register(FluentSQLiteProvider())
    
        /// Register routes to the router
        let router = EngineRouter.default()
        try routes(router)
        services.register(router, as: Router.self)
    
        /// Register middleware
        var middlewares = MiddlewareConfig() // Create _empty_ middleware config
        /// middlewares.use(FileMiddleware.self) // Serves files from `Public/` directory
        middlewares.use(ErrorMiddleware.self) // Catches errors and converts to HTTP response
        services.register(middlewares)
    
        let sqlite: SQLiteDatabase?
        do {
            sqlite = try SQLiteDatabase(storage: .file(path: "runk-3.0-database"))
            print("data base connected") // This gets printed
    
            /// Register the configured SQLite database to the database config.
            var databases = DatabasesConfig()
            databases.add(database: sqlite!, as: .sqlite)
            services.register(databases)
    
            /// Configure migrations
            var migrations = MigrationConfig()
            migrations.add(model: User.self, database: .sqlite)
            services.register(migrations)
        } catch {
            print("couldn't connect") // This doesn't get printed
        }
    }
    

    我做错什么了?

    2 回复  |  直到 6 年前
        1
  •  4
  •   Razib Mollick    6 年前

    正如IMike17所解释的,您的代码只是将新的DB文件创建到Build/Products/Debug或release文件夹中。必须按以下方式动态设置完整路径:

    do {
    let directory = DirectoryConfig.detect()
    let filePath = directory.workDir + "runk-3.0-database"
    sqlite = try SQLiteDatabase(storage: .file(path: filePath)) 
    ......
    
        2
  •  1
  •   IMike17    6 年前

    使用.file(路径:“runk-3.0-database”)方法,如果仅指定名称,则在派生数据文件夹中创建具有指定名称的数据库文件。如果该文件存在于派生数据文件夹中,SQLiteDatabase将使用它。所以在清理build文件夹时,DB会被删除。

    Running default command: /Users/username/Library/Developer/Xcode/DerivedData/SQLiteDB-xxxxxxxxxxxxxxxxxxxxxxx/Build/Products/Debug/

    如果在项目中使用DB的完整路径,则使用该文件。 按如下所示更改init方法,就可以很好地适应本地环境:

    sqlite = try SQLiteDatabase(storage: .file(path: "/Users/rutgerhuijsmans/Documents/runk-3.0/runk-3.0-database"))