访问 Play for Scala 中的默认 JDBC 数据库

Accessing the default JDBC database in Play for Scala

In this Play tutorial 解释了如何使用 JDBC 连接池,包括访问数据库的示例。问题是不清楚如何将默认数据库分配给 db 字段。

例如:

class ScalaControllerInject @Inject() extends Controller {

  def index = Action {
    var outString = "Number is "

    val db: Database = ??? // How to assign the default database to db?

    val conn = db.getConnection()

    try {
      val stmt = conn.createStatement
      val rs = stmt.executeQuery("SELECT 9 as testkey ")

      while (rs.next()) {
        outString += rs.getString("testkey")
      }
    } finally {
      conn.close()
    }
    Ok(outString)
  }

}

我把 db 声明放在方法中而不是 class 参数,但意图是一样的。

注意:我使用的是 Play 2.5.2

当您查看 documentation 时,您可以了解如何在控制器中注入默认数据库(在 application.conf 中配置)。

import javax.inject.Inject

import play.api.Play.current
import play.api.mvc._
import play.api.db._

class ScalaControllerInject @Inject()(db: Database) extends Controller {
  // ...
}

注意 class 声明,其中 @Inject() 后跟注入参数列表。

然后db实例就可以在动作中使用了。

db.withConnection { con: java.sql.Connection =>
  doSomethingWith(con)
}

如果您在应用程序设置中配置了多个数据库,可以使用 NamedDatabase 注释注入正确的数据库。

进口javax.inject.Inject 导入 play.api.db.{ 数据库,命名数据库 } 导入 play.api.mvc.Controller

// inject "orders" database instead of "default"
class ScalaInjectNamed @Inject()(
  @NamedDatabase("orders") db: Database) extends Controller {

  // do whatever you need with the db
}

我在已接受答案的评论中找到了我在对话中寻找的内容。如果您不想使用注入,也可以通过这种方式连接到数据库。您的 SBT .build 必须配置为您拥有的数据库和正确的 JDBC 驱动程序。但是,如果你有那个,那么无论你想在什么 class 中使用数据库,请确保你有:

import play.api.db.Databases

然后你可以:

class ExampleClass {

  val testDb = Databases(
    driver = "org.postgresql.Driver",
    url = "postgres://dbUserName:password@localhost:port#/name_of_db"
  )

这将允许您像其他方式一样使用 testDb 对象。