简体   繁体   中英

JDBC connection in Play Framework 2.6

I am using Play-2.6 and want to connect Play application to postgreSQL.

In application.conf file I have

play.db { 

  # The combination of these two settings results in "db.default" as the
  # default JDBC pool:
  config = "db"
  default = "default"

  default.driver = org.postgresql.Driver
  default.url = jdbc:postgresql://localhost:5432/mydb1
  default.username = "postgres"
  default.password = "postgres"

} 

In build.sbt file I have

libraryDependencies += jdbc
libraryDependencies +="org.postgresql" % "postgresql" % "9.4-1206-jdbc42" <br/>

In a service class RadioParameters.scala I am trying to access the DB using

import models._
import play.api.db._
import java.sql._
import java.sql.Connection
import java.sql.DriverManager._


class RadioParameters(_ap_mac_id:String) {
         val ap_mac_id =_ap_mac_id

  def radioparameters:radio = {

                **val connection =  DB.getConnection()**
                .....
  }

and I am getting error:

**\RadioParameters.scala:38:35: not found: value DB
val connection =  DB.getConnection() <br/>**

I tried replacing it with Database, db but nothing seems to work. I have seen accessing DB like this somewhere on web. I checked play-jdbc-api_2.12-2.6.7 in Eclipse.It doesn't contain any DB class or object.

How do I get this thing working ?
Any kind of link or suggestion is totally appreciable.

Play 2.6 uses dependency injection and DB is not available anymore, try something like:

@Singleton
class RadioParameters @Inject()(db: DBApi) {
  val dbName = "default"

  def radioparameters():radio = {
    db.database(dbName).withConnection(implicit connection =>
      //db call
    )
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM