Question

I am using Anorm for querying a MySQL database from Playframework 2.1. I created a prepared statement like this.

import play.api.db.DB
import anorm._

val stat = DB.withConnection(implicit c => SQL("SELECT name, email FROM user WHERE id=?").filledStatement)

Now how do I use it? Am I event doing this right? I am totally ignorant of the anorm API and I already went through the source code without gaining much insight.

Code examples are more that welcome.

Was it helpful?

Solution

A good example on the Anorm usage is given in the respective tutorial. It also contains some examples that pass dynamic parameters to the queries. You should start by writing your query and replace declare placeholders like {somePlaceholder} in the query string. You can later assign values using the .on() method like this:

SQL(
  """
    select * from Country c 
    join CountryLanguage l on l.CountryCode = c.Code 
    where c.code = {countryCode};
  """
).on("countryCode" -> "FRA")

Or in your case:

import play.api.db.DB
import anorm._

val stat = DB.withConnection(implicit c =>
  SQL("SELECT name, email FROM user WHERE id={id}").on("id" -> 42)
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top