Search code examples
databasescalaplayframework-2.3

How do I use another database other than default in play-framework?


Up until I was using only one database in my application. So for any sql query, I was just using the default database. Below is given the info about the database.

db.default.driver=org.postgresql.Driver
db.default.url="postgres://user:password@localhost:5439/database_name"

These info are saved in the appliction.conf file. In the code below DB is the default database.

DB.withConnection {
  conn =>
    {
      val statement = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)
      try {
        statement.execute(sql)
      }
      catch {
        case e: Exception => Logger.debug("There is some error with the database")
      }
    }
}

But I need to use another database. Below is given the info about the database.

db.um.driver=com.mysql.jdbc.Driver
db.um.url="mysql://user:password@localhost:3306/database_name"

These info are also saved in the application.conf file. Now how do I access that database and run an sql command.


Solution

  • The data source called default, as the name suggests, is used as a default value for all connections. You can see that the withConnection() method takes a parameter with a data source name but if nothing is passed, "default" is used instead.

    To use your additional data source you have to specify it as a parameter of the withConnection() method.

    DB.withConnection("um") { conn =>
      // implement your action
    }