日期:2014-05-20 浏览次数:21073 次
上一节我们制作了一个简单的留言板程序,数据是存在内存里的,重启play服务后留言信息会丢失。现在我们来把留言信息存储在MySQL数据库里。
单击右边链接复习上一节: Play framework 2.0入门教程(三)
我们在上一节留言板的基础上进行修改,如果没有源代码,先下载源码
cd todolist play run

# db.default.driver=org.h2.Driver # db.default.url="jdbc:h2:mem:play"上面的驱动程序定义是h2数据库的,我们做一些改动,让他变成MySQL数据库的
db.default.driver=com.mysql.jdbc.Driver db.default.url="mysql://root:root@localhost/todolist"其中root:root分别为MySQL数据库的用户名和密码,todolist是数据库名
val appDependencies = Seq(
// Add your project dependencies here,
"mysql" % "mysql-connector-java" % "5.1.18"
)reload update
# todolist schema
# ---!Ups
CREATE TABLE message(
id int NOT NULL auto_increment,
label varchar(255),
primary key(id)
);
# ---!Downs
DROP TABLE message;
mysql -u root -proot
create database todolist CHARACTER SET 'utf8' COLLATE 'utf8_general_ci';

use todolist; show tables; decribe message;会发现play已经自动为我们按要求创建好表,如下图所示:

import play.api.data._
import play.api.data.Forms._
import play.api.db._
import play.api.Play.current
import anorm._
import anorm.SqlParser._
case class Message(id:Long,label:String)
object Message{
val message={
get[Long]("id")~
get[String]("label") map{
case id~label=>Message(id,label)
}
}
def all():List[Message]=DB.withConnection{implicit c=>
SQL("select * from task").as(message*)
}
def create(label:String){
DB.withConnection{implicit c=>
SQL("insert into task(label) values ({label})").on(
'label->label
).executeUpdate()
}
}
def delete(id:Long){
DB.withConnection{implicit c=>
SQL("delete from task where id={id}").on (
'id->id
).executeUpdate()
}
}
val messageForm=Form(
"label"->nonEmptyText
)
}


