Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Anorm outside of Play?

How do you use Anorm outside of play in Scala? In the Anorm document for play, it simply uses something like:

DB.withConnection { implicit c =>
  val result: Boolean = SQL("Select 1").execute()    
} 

The DB object is only for Play. How do you use Anorm alone without using Play?

like image 498
Daniel Wu Avatar asked Aug 30 '14 13:08

Daniel Wu


2 Answers

There is no need of DB object (part of Play JDBC not Anorm). Anorm works as along as you provide it connection as implicit:

implicit val con: java.sql.Connection = ??? // whatever you want to resolve connection

SQL"SELECT * FROM Table".as(...)

You can resolve JDBC connection in many way: basic DriverManager.getConnection, JNDI, ...

As for dependency, it's easy to add it in SBT: How to declare dependency on Play's Anorm for a standalone application? .

like image 163
cchantep Avatar answered Oct 11 '22 15:10

cchantep


You could also emulate the DB object as follows (i haven't tried this though)

 object DB {
    def withConnection[A](block: Connection => A): A = {
      val connection: Connection = ConnectionPool.borrow()

      try {
        block(connection)
      } finally {
        connection.close()
      }
    }
  }

Taken from https://github.com/TimothyKlim/anorm-without-play/blob/master/src/main/scala/Main.scala

like image 36
Faheem Sohail Avatar answered Oct 11 '22 13:10

Faheem Sohail