Carregar apresentação
A apresentação está carregando. Por favor, espere
PublicouAna do Carmo Palhares Amaro Alterado mais de 6 anos atrás
1
Play 2.0 com Scala Banco de Dados
2
Configurando o Banco de Dados
Arquivo conf/application.conf Banco de Dados H2 usando a memória db.default.driver=org.h2.Driver db.default.url="jdbc:h2:mem:play" Banco de Dados H2 usando arquivos db.default.driver=org.h2.Driver db.default.url="jdbc:h2:/path/to/db-file"
3
Configurando o MySQL Arquivo conf/application.conf
# Default database configuration using MySQL database engine # Connect to playdb as playdbuser db.default.driver=com.mysql.jdbc.Driver db.default.url="jdbc:mysql://localhost/playdb" db.default.user=playdbuser db.default.pass="a strong password" Arquivo project/Build.scala val appDependencies = Seq( "mysql" % "mysql-connector-java" % "5.1.21" )
4
Obtendo uma Conexão JDBC
A forma mais simples import play.api.db._ val conexao = DB.getConnection() ... conexao.close() Alternativa: O Play fecha a conexão automaticamente DB.withConnection { conexao => }
5
Anorm API de acesso a dados usando SQL
6
Executando SQL import anorm._ import play.api.db.DB DB.withConnection { implicit c => val result: Boolean = SQL("Select 1").execute() }
7
Executando SQL Execute() – Devolve um booleano indicando o sucesso
val result: Boolean = SQL("Select 1").execute() ExecuteUpdade() – Devolve o número de linhas afetadas val result: Int = SQL("delete from City where id = 99").executeUpdate() ExecuteInsert() – Inserir um registro com chave auto-gerada val id: Option[Long] = SQL( "insert into City(name, country) values ({name}, {country})") .on("Cambridge", "New Zealand").executeInsert()
8
Executando SQL Scala suporta Strings com várias linhas
val sqlQuery = SQL( """ select * from Country c join CountryLanguage l on l.CountryCode = c.Code where c.code = 'FRA'; ) SQL com parâmetros dinâmicos SQL( where c.code = {countryCode}; ).on("countryCode" -> "FRA")
9
Recuperando Informações
Apply() devolve uma lista preguiçosa com o resultado // Create an SQL query val selectCountries = SQL("Select * from Country") // Transform the resulting Stream[Row] to a // List[(String,String)] val countries = selectCountries().map(row => row[String]("code") -> row[String]("name") ).toList
10
Recuperando Informações
Contando a quantidade de linhas de uma tabela // First retrieve the first row val firstRow = SQL( "Select count(*) as c from Country“ ).apply().head // Next get the content of the 'c' column as Long val countryCount = firstRow[Long]("c")
11
Lidando com campos nulos
O código a seguir pode gerar uma exceção UnexpectedNullableFound(COUNTRY.INDEPYEAR) SQL("Select name,indepYear from Country")().map {row => row[String]("name") -> row[Int]("indepYear") } Usando Option SQL("Select name,indepYear from Country")().map{ row => row[String]("name") -> row[Option[Int]]("indepYear")
Apresentações semelhantes
© 2024 SlidePlayer.com.br Inc.
All rights reserved.