SLICK基础
1.sbt添加依赖
"com.typesafe.slick" %% "slick" % "3.2.3", "org.slf4j" % "slf4j-nop" % "1.6.4", "com.typesafe.slick" %% "slick-hikaricp" % "3.2.3", "mysql" % "mysql-connector-java" % "5.1.47",
2.数据库配置:src/main/resources/application.conf
indie-db = { url = "jdbc:mysql://devhdp3:3307/indie?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&noAccessToProcedureBodies=true&useSSL=false" driver = "com.mysql.jdbc.Driver" keepAliveConnection = true user = "root" password = "123456" connectionPool = disabled connectionTestQuery = "SELECT 1" connectionTimeout = 30 second }
3.代码
package org.netsharp.persist import slick.jdbc.MySQLProfile.api._ import scala.concurrent.duration._ import scala.concurrent.{Await, Future} object Db2 { //实体定义 final case class Message( sender: String, content: String, id: Long = 0L) //元数据定义 final class MessageTable(tag: Tag) extends Table[Message](tag, "message") { def id = column[Long]("id", O.PrimaryKey, O.AutoInc) def sender = column[String]("sender") def content = column[String]("content") def * = (sender, content, id).mapTo[Message] } def main(args:Array[String]): Unit ={ val messages = TableQuery[MessageTable] //数据库访问对象 val db = Database.forConfig("indie-db") //创建表 val setupFuture = db.run(messages.schema.create) val result = Await.result(setupFuture, 5.seconds) //插入数据 def freshTestData = Seq( Message("Dave", "Hello, HAL. Do you read me, HAL?"), Message("HAL", "Affirmative, Dave. I read you."), Message("Dave", "Open the pod bay doors, HAL."), Message("HAL", "I'm sorry, Dave. I'm afraid I can't do that.") ) val insert: DBIO[Option[Int]] = messages ++= freshTestData val result2: Future[Option[Int]] = db.run(insert) val rowCount = Await.result(result2, 2.seconds) //查询数据 val halSays = messages.filter(_.sender === "HAL").result val messagesFuture: Future[Seq[Message]] = db.run(halSays) val list = Await.result(messagesFuture, 2.seconds) list.foreach(println) } }
4.上面例子是基于mysql的,对于sqlserver需要如下修改
a,sbt添加sqlserver的jdbc包依赖:"com.microsoft.sqlserver" % "mssql-jdbc" % "7.0.0.jre8",
b.添加配置
indie-sqlserver = { url = "jdbc:sqlserver://host_or_ip;database=REMInformation;useUnicode=true&characterEncoding=UTF-8" driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver" keepAliveConnection = true user = "xxxx" password = "xxxx" connectionPool = disabled connectionTestQuery = "SELECT 1" connectionTimeout = 30 second }
c.代码中原来的import
import slick.jdbc.MySQLProfile.api._
改成新的import
import slick.jdbc.SQLServerProfile.api._
d.代码中原来的数据库配置读取
val db = Database.forConfig("indie-db")
改为
val db = Database.forConfig("indie-sqlserver")
作者 :秋时
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。