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

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

object BasicExample {
def main(args: Array[String]) {
// 这个Parser我发现好像用不了。。
val configuration = URLParser.parse("")
val connection: Connection = new PostgreSQLConnection(configuration) //阻塞等待连接
Await.result(connection.connect, seconds) //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()
}
//注意,这里的-1是Any而不是Future[Any]
case None => -
}) val result = Await.result(mapResult, seconds)
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()) object MessageRepository {
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的意思
class MessageRepository(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()))
case None => None
}
}
} private def rowToMessage(row: RowData): Message = {
new Message(
id = Some(row("id".asInstanceOf[Long]))
content = row("content").asInstanceOf[String]
moment = row("moment").asInstanceOf[LocalDate]
)
}
}

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

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

object Global extends GlobalSettings {
private val databaseConfiguration = System.getenv("DATABASE_URL") match {
case url: String => URLParser.parse(url)
case _ => new Configuration(
username = "postgres"
database = Some("databasename")
port =
)
} // factory 还有mysql专用版么
private val factory = new PostgreSQLFactory(databaseConfiguration)
private val pool = new ConnectionPool(factory, PoolConfiguration.Default)
val messageRepository = new MessageRepository( pool ) // play 的东西,普通的程序不晓得如何处理close问题
override def onStop(app: Application)
pool.close
}

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

mysql asyn 示例的更多相关文章

  1. JAVA使用jdbc连接MYSQL简单示例

    以下展示的为JAVA使用jdbc连接MYSQL简单示例: import java.sql.DriverManager; import java.sql.ResultSet; import java.s ...

  2. Mysql语句示例

    Mysql语句示例 最常用 sql 语句总结 前言 Mysql 是数据库开发使用的主要平台之一.sql 的学习掌握与使用是数据库开发的基础,此处展示详细sql 语句的写法,及各种功能下的 sql 语句 ...

  3. MySQL安装示例数据库

    MySQL安装示例数据库 本文档演示如何下载及安装MySQL示例数据库sakila及employees数据库 1. 安装sakila数据库 1.1 下载sakila数据库 wget http://do ...

  4. mysql死锁示例

    MySQL有三种锁的级别:页级.表级.行级. MyISAM和MEMORY存储引擎采用的是表级锁(table-level locking):BDB存储引擎采用的是页面锁(page-level locki ...

  5. 创建MySQL存储过程示例

    创建MySQL存储过程是学习MySQL数据库必须要掌握的知识,下文对创建MySQL存储过程作了详细的介绍,供您参考学习. AD:2013大数据全球技术峰会课程PPT下载 下文将教您如何创建MySQL存 ...

  6. mysql 视图示例

    基本操作 建立视图 CREATE VIEW view_test(qty,price,total) AS SELECT quantity,price,quantity*price FROM t; 多表视 ...

  7. SpringBoot+MyBatis+Mysql 详细示例

    SpringBoot与MyBatis整合,底层数据库为mysql的使用示例  项目下载链接:https://github.com/DFX339/bootdemo.git   新建maven项目,web ...

  8. mysql 函数示例(转)

    MySQL函数大全及用法示例 1.字符串函数ascii(str)   返回字符串str的第一个字符的ascii值(str是空串时返回0)  mysql> select ascii('2');   ...

  9. MySQL操作示例

    """ MySQL综合练习作业 """ # 1.自行创建测试数据: # 创建数据库 """ create da ...

随机推荐

  1. Nexus 7更换NFC控制器,导致不再支持读取Mifare Classic NFC 1k Tags

    In a review conducted by Anandtech, it was found that the Nexus 4 makes use of the Broadcom BCM20793 ...

  2. Redis源码研究—基础知识

    1. Redis 是什么 Redis是一个开源的使用ANSI C语言编写的基于内存的key/value存储系统,与memcache类似,但它支持的value类型更多,包括:字符串(string).链表 ...

  3. 配置nginx

    咱不玩服务器,只在把人家的配置拷贝一份,建个自己的测试服务器 1. 如果nginx已配置(相当于windows在环境变量中配置了path吧) 查找nginx配置路径: whereis nginx 一般 ...

  4. 递归 - 求 n 个球中取 m 个不同的球,有多少种取法?

    代码: #include <iostream> using namespace std; int F(int _n, int _m) { if(_n < _m) return 0; ...

  5. 微信小程序——倒计时功能

    做小程序项目中,需要做一个倒计时功能,如下图: 记录一下实现步骤: 1.考虑到这个功能可能会有多处用到,所以把倒计时的函数写在utils.js里面: const formatNumber = n =& ...

  6. R语言-向量化操作(apply、tapply、lapply、sapply、mapply、table等)

    一.apply函数(对一个数组按行或者按列进行计算): 使用格式为:apply(X, MARGIN, FUN, ...) 其中X为一个数组:MARGIN为一个向量(表示要将函数FUN应用到X的行还是列 ...

  7. Sword protobuf学习二

    编写protobuf消息文件 文件格式: xxx.proto //标明使用哪个版本的protobuf,默认2.0版本 syntax = "proto3"; //类似于c++中的na ...

  8. [Forward]Ten Caching Mistakes that Break your App

    Caching large objects, duplicate objects, caching collections, live objects, thread unsafe caching a ...

  9. 简单MVVM教程

    WPF+MVVM的本地桌面程序为背景,这样一来我们可以不去操心服务器那部分的事情,更加专注我们的MVVM.我打算把最重要的部分放到开头来讲,而接下来这最重要的部分却是全篇教程唯一没有代码的部分.好,下 ...

  10. SSh on Ubuntu

    ssh程序分为有客户端程序openssh-client和服务端程序openssh-server.如果需要ssh登陆到别的电脑,需要安装openssh-client,该程序Ubuntu是默认安装的.而如 ...