存取SQL資料庫

Accessing an SQL database,  https://github.com/playframework/Play20/wiki/ScalaDatabase

$ play run
[info] Loading project definition from /home/chaoyi/p2/s1/project
[info] Set current project to s1 (in build file:/home/chaoyi/p2/s1/)

--- (Running the application from SBT, auto-reloading is enabled) ---

[info] play - Listening for HTTP on port 9000...

(Server started, use Ctrl+D to stop and go back to the console...)

[info] play - database [default] connected at jdbc:h2:mem:play
[info] play - Application started (Dev)



Configuring JDBC connection pools

Play 2.0 provides a plug-in for managing JDBC connection pools. You can configure as many databases you need.

To enable the database plug-in, configure a connection pool in the conf/application.conf file. By convention, the default JDBC data source must be called default:

# Default database configuration
db.default.driver=org.h2.Driver
db.default.url=jdbc:h2:mem:play

To configure several data sources:

# Orders database
db.orders.driver=org.h2.Driver
db.orders.url=jdbc:h2:mem:orders

# Customers database
db.customers.driver=org.h2.Driver
db.customers.url=jdbc:h2:mem:customers

If something isn’t properly configured you will be notified directly in your browser:

Accessing the JDBC datasource

The play.api.db package provides access to the configured data sources:

import play.api.db._

val ds = DB.getDatasource()

Obtaining a JDBC connection

There is several ways to retrieve a JDBC connection. The first is the most simple:

val connection = DB.getConnection()

But of course 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:

DB.withConnection { conn =>
  // do whatever you need with the connection
}

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

Tip: Each Statement and ResultSet created with this connection will be closed as well.

A variant is to set the connection auto-commit to false automatically and to manage a transaction for the block:

DB.withTransaction { conn =>
  // do whatever you need with the connection
}

Next: Using Anorm to access your database



子網頁 (2): h2-browser PostgreSQL
Comments