我是Vapor的新手,我想尝试连接MySQL数据库。我在官方文档中找到了解决方法,但是当我尝试发送查询时会抛出错误:
No services are available for 'DatabaseConnectionPoolCache'. (Container.swift:112)
我只是从文档中复制粘贴代码,所以它不起作用。有人可以帮我找出原因吗?
我在 Mojave 上具有 MySQL@5.7 。实际上,简单的请求可以很好地工作,例如:
router.get("hey") { req in
return "Stas, hey"
}
configure.swift中的代码:
import FluentSQLite
import MySQL
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())
try services.register(MySQLProvider())
/// 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)
// Configure a SQLite database
let sqlite = try SQLiteDatabase(storage: .memory)
/// 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: Todo.self, database: .sqlite)
services.register(migrations)
//Configure a MySQL database
let mysql = try MySQLDatabase(config: MySQLDatabaseConfig(
hostname: "127.0.0.1",
port: 3306,
username: "root",
password: "7374",
database: "WORK_TIME"))
///Register to the congig
var mysqlDatabases = DatabasesConfig()
mysqlDatabases.add(database: mysql, as: .mysql)
services.register(mysqlDatabases)
}
我在main.swift中的查询:
public struct MySQLVersion: Codable {
let version: String
}
router.get("sql") { req in
return req.withPooledConnection(to: .mysql) {conn in
return conn.raw("SELECT @@version as version")
.all(decoding: MySQLVersion.self)
}.map { rows in
return rows[0].version
}
}
它应该返回我的MySQL版本,但是会引发一个奇怪的错误。
答案 0 :(得分:2)
您的问题是原始项目模板中有一些剩余的SQLite内容。
首先从您的fluent-sqlite
文件中删除Package.swift
依赖项,并从任何目标依赖项中删除FluentSQLite
目标。然后在终端中运行swift package update
(如果使用Xcode,则运行vapor xcode
。
现在您已经从项目中删除了FluentSQLite
依赖项,那么您应该能够遵循编译器错误来解决您的问题。这是我找到的:
import FluentSQLite
import MySQL
应该是:
import FluentMySQL
try services.register(FluentSQLiteProvider())
try services.register(MySQLProvider())
应该是
try services.register(FluentMySQLProvider())
删除此内容,因为您使用的是MySQL而不是SQLite:
// Configure a SQLite database
let sqlite = try SQLiteDatabase(storage: .memory)
/// Register the configured SQLite database to the database config.
var databases = DatabasesConfig()
databases.add(database: sqlite, as: .sqlite)
services.register(databases)
migrations.add(model: Todo.self, database: .sqlite)
应该是
migrations.add(model: Todo.self, database: .mysql)
我认为这涵盖了所有内容。您的/sql
路线现在应该可以使用。
答案 1 :(得分:1)
要解决此问题,您应该摆脱原始项目中所有剩余的SQLite内容,并必须在routes.swift
中写出路由