我正在编写一个简单的scala脚本来使用slick 3连接到Mysql。
我的 build.sbt 如下所示:
name := "slick_sandbox"
version := "1.0"
scalaVersion := "2.11.7"
libraryDependencies ++= Seq(
"com.typesafe.slick" %% "slick" % "3.0.3",
"org.slf4j" % "slf4j-nop" % "1.6.4",
"mysql" % "mysql-connector-java" % "5.1.6"
)
application.conf :
Drivder
是故意的错误;另外,我没有提供db用户名或密码!
mysqldb = {
url = "jdbc:mysql://localhost/slickdb"
driver = com.mysql.jdbc.Drivder
connectionPool = disabled
keepAliveConnection = true
}
Main.scala
import slick.driver.MySQLDriver.api._ import scala.concurrent.ExecutionContext.Implicits.global
object Main {
def main(args: Array[String]) {
// test to see this function is being run; it IS
println("foobar")
// I expected an error here due to the intentional
// mistake I've inserted into application.conf
// I made sure the conf file is getting read; if I change mysqldb
// to some other string, I get correctly warned it is not a
// valid key
val db = Database.forConfig("mysqldb")
val q = sql"select u.name from users ".as[String]
db.run(q).map{ res=>
println(res)
}
}
}
编译好。现在这个是我在终端上运行sbt run
时看到的结果:
felipe@felipe-XPS-8300:~/slick_sandbox$ sbt run
[info] Loading project definition from /home/felipe/slick_sandbox/project
[info] Set current project to slick_sandbox (in build file:/home/felipe/slick_sandbox/)
[info] Compiling 1 Scala source to /home/felipe/slick_sandbox/target/scala-2.11/classes...
[info] Running Main
foobar
[success] Total time: 5 s, completed Sep 17, 2015 3:29:39 AM
一切看起来都不错;即使我在一个不存在的数据库上明确地运行了查询,但是光滑仍然没有发生任何事情。
我在这里缺少什么?
答案 0 :(得分:2)
Slick异步运行查询。所以它没有足够的时间来执行它。在你的情况下,你必须等待结果。
object Main {
def main(args: Array[String]) {
println("foobar")
val db = Database.forConfig("mysqldb")
val q = sql"select u.name from users ".as[String]
Await.result(
db.run(q).map{ res=>
println(res)
}, Duration.Inf)
}
}