以postgresql为例,使用slick orm工具进行scala数据库操作
name := "Simple Project"
version := "1.0"
scalaVersion := "2.10.3"
libraryDependencies ++= List(
"com.typesafe.slick" %% "slick" % "2.0.2-RC1",
"org.slf4j" % "slf4j-nop" % "1.6.4"
)
package com.xueyu
import scala.slick.driver.PostgresDriver.simple._
import java.sql.{Timestamp, Time, Date}
import java.text.SimpleDateFormat
case class TestCase(name: String, count: Int, time: Timestamp)
class TestTable(tag:Tag) extends Table[TestCase](tag, "mytestscaladb1") {
def name = column[String]("name", O.PrimaryKey)
def count = column[Int]("count")
def time = column[Timestamp]("time")
def * = (name, count, time) <> (TestCase.tupled, TestCase.unapply)
}
object mydbtest {
def main(args: Array[String]) {
val db = Database.forURL(url = "jdbc:postgresql://172.18.2.180:5432/scaladb?user=postgres&password=password", driver = "org.postgresql.Driver")
val tsFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
def ts(str: String) = new Timestamp(tsFormat.parse(str).getTime)
val MyTests = TableQuery[TestTable]
db withSession { implicit session: Session =>
MyTests forceInsertAll(TestCase("xueyu", 37, ts("2013-12-01 11:00:00")))
MyTests += TestCase("wo de ceshi", 101, ts("2014-02-28 23:02:02"))
MyTests += TestCase("datetime test", 121, ts("2014-04-09 10:02:27"))
println("mytestscaladb:")
MyTests foreach { case TestCase(name, count, time) =>
println(" " + name + "\t" + count + "\t" + time)
}
val q1 = (for {
c <- MyTests
} yield (c.count))
q1 foreach { case (count) =>
println("q1 query:" + count)
}
}
}
}
建立lib目录,下载较新版本的postgresql-jdbc driver至lib目录,这里下载的是postgresql-9.3-1101.jdbc4.jar
在build.sbt中使用libraryDependency下载的driver比较老,不能用
在build.sbt中的libraryDependencies 中添加 "com.github.tminglei" % "slick-pg_2.10" % "0.5.3"
扩展后的driver是
package com.xueyu
import scala.slick.driver.PostgresDriver
import com.github.tminglei.slickpg._
trait MyPostgresDriver extends PostgresDriver
with PgArraySupport
with PgDateSupport
with PgRangeSupport
with PgHStoreSupport
with PgSearchSupport {
///
override val Implicit = new ImplicitsPlus {}
override val simple = new SimpleQLPlus {}
//
trait ImplicitsPlus extends Implicits
with ArrayImplicits
with DateTimeImplicits
with RangeImplicits
with HStoreImplicits
with SearchImplicits
trait SimpleQLPlus extends SimpleQL
with ImplicitsPlus
with SearchAssistants
}
object MyPostgresDriver extends MyPostgresDriver
在相关数据库中建立数据表"mytestscaladb1",分别有name varchar(20), count integer, time timestamp域类型,使用sbt compile, sbt run运行程序