问题
I'm writing a veery simple scala script to connect to Mysql using slick 3.
My build.sbt looks like this:
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
is an intentional mistake; also, I did not provide a db username or password!
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)
}
}
}
It compiles OK. Now this is the result I see when I run sbt run
on the terminal:
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
Everything looks deceptively OK; even though I explicitly ran the query on a database that doesn't exist, slick went ahead as if nothing has happened.
What am I missing here?
回答1:
Slick runs queries asynchronously. So it just didn't have enough time to execute it. In your case you have to wait for result.
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)
}
}
来源:https://stackoverflow.com/questions/32623875/connecting-to-mysql-using-slick-3-0-no-username-no-password-and-bogus-driver