Home » TechNote » Play Framework: Accessing an SQL Database

Play Framework: Accessing an SQL Database

Hi all,

As you know, Play is an open source web application framework, written in Scala and Java, which follows the model–view–controller (MVC) architectural pattern. It aims to optimize developer productivity by using convention over configuration, hot code reloading and display of errors in the browser.

Today I will introduce a basic concept of this framework, it is how to access an SQL database.

Firstly, all things you need is:

  • IntelliJ IDEA (http://www.jetbrains.com/idea/download/)
  • Scala plugin (enable through IntelliJ IDEA)
  • Play Framework (enable through IntelliJ IDEA)
  • Mysql
After these materials above has been installed and run successfully, now we will focus on major part of this blog, how to connect and interactive to dabase using Play Framework based on Scala language.

Configuring JDBC connection pools

Play provides a plug-in for managing JDBC connection pools. You can configure as many databases as you need.
You must configure a connection pool in the conf/application.conf file. By convention, the default JDBC data source must be called default and the corresponding configuration properties are db.default.driver and db.default.url.

MySQL database engine connection properties

Play can support H2, SQLite, PostGreSQL and MySQL engine but in my case I use MySQL database, these lines below is configuration for MySQL database engine

Obtaining a JDBC connection

There are several ways to retrieve a JDBC connection. The simplest way is:

But after some SQL query execution you need to call close() at some point on the opened connection to return it to the connection pool. Another way is to let Play manage closing the connection for you:

The connection will be automatically closed at the end of the block.

Using Anorm to access your database

Play includes a simple data access layer called Anorm that uses plain SQL to interact with the database and provides an API to parse and transform the resulting datasets.

Anorm is Not an Object Relational Mapper

Add Anorm to your project

You will need to add Anorm and jdbc plugin to your dependencies :

Executing SQL queries with Anorm

You need to import anorm._ to use SQL object to create queries and play.api.db.DB to retrieve results of the query

The execute method indicate that whether the execution was succeful.

To execute an update, you can use executeUpdate()

The query above will delete the record which have id equal 99 and return result is number of affected rows

If you are inserting data that has an auto-generated Long primary key, you can call executeInsert()

That is only some simple examples about how to use Anorm to interactive with DB in Play framework. We will continue to investigate and execute some complex concepts of Anorm in next blog

================================
Ref: Accessing an SQL database

Tagged width:, ,