mysql asyn_mysql asyn 示例

这篇文章摘自mysql asyn作者的博客,博客地址

开头有一个简单示例,然后是一个在play上的应用。例子我并没有跑过,但是仍能学到不少东西。

objectBasicExample {

def main(args: Array[String]) {//这个Parser我发现好像用不了。。

val configuration = URLParser.parse("")

val connection: Connection= newPostgreSQLConnection(configuration)//阻塞等待连接

Await.result(connection.connect, 5seconds)//sendQuery直接就执行了,不像slick那样,还要单独的run

val future: Future[QueryResult] = connection.sendQuery("SELECT * FROM USERS")

val mapResult: Future[Any]= future.map(queryResult =>queryResult.rows match {case Some(resultSet) =>{

val row: RowDat=resultSet.head

row(0)

}//注意,这里的-1是Any而不是Future[Any]

case None => -1})

val result= Await.result(mapResult, 5seconds)

println(result)//关闭数据库链接

connection.disconnect

}

}

The basic usage pattern is quite simple, you ask for something, you get a future[_] back. The PostgreSQLConnection is a real connection to database. it implements the Connection trait and you should try to use the trait as much as possible.

When you create a connection handler, it's not connected to the db yet, you have to connect it yourself calling connect and waiting for the future to return or composing on the future to do something else.

下面是一个play app. 包括MVC模型。因为Controller牵扯了太多play的知识,我就暂时不抄了,只把持久化部分写上。

这个持久化实现了ResultSet到case class的mapping,虽然是手动进行的,但是写的非常好。如果能使用implicit写mapping应该会更加优雅。

此外,一个play app应该选用connection pool而不是每次用到数据库都重新建立连接。下面给出了用法。

//需要提前创建好数据库,id应该是自增的

case class Message(id: Option[Long], content: String: LocalDate =LocalDate.now())objectMessageRepository {

val Insert= "INSERT INTO messages (content, moment) VALUES(?, ?)"val Update= "UPDATE messages SET content = ?, moment = ? WHERE id = ?"val Select= "SELECT id, content, moment FROM messages ORDER BY id asc"val SelectOne= "SELECT id, content, momment FROM messages WHERE id = ?"}//这个有点dependency injection的意思

classMessageRepository(pool: Content) {

import MessageRepository._

def save(m: Message): Future[Message]={//queryResult => m 是什么意思

case Some(id) =>pool.sendPreparedStatement(Update, Array(m.content, m.moment, id)).

map { queryResult=>m }case None =>pool.sendPreparedStatement(Insert, Array(m.content, m.moment)).

map { queryResult=>m }

}

def list: Future[IndexSeq[Message]]={

pool.sendQuery(Select). map {//rows 返回resultSet, get返回什么呢,返回的是 Iterator 类型的东西么

queryResult => queryResult.rows.get.map {

item=>rowToMessage(item)

}

}

}

def find(id: Long): Future[Option[Message]]={//[Any] 非得加么

pool.sendPreparedStatement(SelectOne, Array[Any](id)).map {

queryResult=>queryResult.rows match {case Some(rows) =>Some(rowToMessage(rows.apply(0)))case None =>None

}

}

}private def rowToMessage(row: RowData): Message ={newMessage(

id= Some(row("id".asInstanceOf[Long]))

content= row("content").asInstanceOf[String]

moment= row("moment").asInstanceOf[LocalDate]

)

}

}

对于mysql的每一张表,都应该有一个这样的插入语句,对于多表join的情况,可能要单独处理吧。

上面实现了DAO,下面一小段代码可以充当配置文件来用,相当于dependency injection

objectGlobal extends GlobalSettings {private val databaseConfiguration = System.getenv("DATABASE_URL") match {case url: String =>URLParser.parse(url)case _ => newConfiguration(

username= "postgres"database= Some("databasename")

port= 5433)

}//factory 还有mysql专用版么

private val factory = newPostgreSQLFactory(databaseConfiguration)private val pool = newConnectionPool(factory, PoolConfiguration.Default)

val messageRepository= newMessageRepository( pool )//play 的东西,普通的程序不晓得如何处理close问题

overridedef onStop(app: Application)

pool.close

}

对于一般的程序,用connectionPool要好一点,但是要注意,不能直接在connectionPool上应用transacation。当需要用到transacation时,从connectionPool中获取一个connection,还要记得还回去。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值