在 Slick 中连接到 SQLite 数据库不起作用但不会引发错误
Connect to SQLite database in Slick doesn't work but doesn't throw an error
所以 Typesafe 的 Slick 的文档非常薄,它的示例是针对 Play 的,这对在 Eclipse 中工作没有多大帮助。
我尝试连接到我系统上现有的 SQLite 数据库,它包含一个 table "Maintenance_Request"。
import slick.driver.SQLiteDriver.api._
import scala.concurrent.ExecutionContext.Implicits.global
object starter {
def main(args: Array[String]): Unit = {
val db = Database.forURL("jdbc:sqlite:/home/sq/workspace/dbFun/IOdb.db", driver = "org.sqlite.JDBC")
val action = sql"select CATEGORY from MAINTENANCE_REQUEST".as[(Int)]
db.run(action).foreach(println)
}
}
虽然启动程序并没有给我任何结果。另外,如果我更改路径,比如遗漏一个字符,那么它不是有效路径,也不会抛出错误!所以我不知道什么有效,什么无效。
有没有办法知道变量 db 是否连接到数据库?
有什么方法可以知道 Database.forURL 成功还是失败了??
我怀疑您看不到结果的原因只是您的主程序在查询完成之前完成了。
我的意思是,db.run(action)
的类型将是 Future[Seq[Int]]
。调用 foreach
不会阻塞结果。 foreach
在 Future
上的行为在此处记录:
It is important to note that calling the foreach combinator does not block to traverse the value once it becomes available. Instead, the function for the foreach gets asynchronously executed only if the future is completed successfully.
-- http://docs.scala-lang.org/overviews/core/futures.html
所以你能做的就是等待结果:
import scala.concurrent.Await
import scala.concurrent.duration._
val result = Await.result(db.run(action), 2 seconds)
result.foreach(println)
...这将确保您在程序终止之前看到打印的结果。
关于连接到数据库的错误...
- 在
forUrl
中,如果连接字符串不是有效的识别方案,您将看到一个异常,例如 java.sql.SQLException: No suitable driver
- 如果您提供了有效的 URL,但数据库名称错误,这将取决于所讨论的数据库。对于 H2,我怀疑是 SQLite,您可能会创建一个新的空数据库。您可以在 JDBC URL 中传递一些参数来控制此行为,但这将是 driver/database 特定的。
所以 Typesafe 的 Slick 的文档非常薄,它的示例是针对 Play 的,这对在 Eclipse 中工作没有多大帮助。
我尝试连接到我系统上现有的 SQLite 数据库,它包含一个 table "Maintenance_Request"。
import slick.driver.SQLiteDriver.api._
import scala.concurrent.ExecutionContext.Implicits.global
object starter {
def main(args: Array[String]): Unit = {
val db = Database.forURL("jdbc:sqlite:/home/sq/workspace/dbFun/IOdb.db", driver = "org.sqlite.JDBC")
val action = sql"select CATEGORY from MAINTENANCE_REQUEST".as[(Int)]
db.run(action).foreach(println)
}
}
虽然启动程序并没有给我任何结果。另外,如果我更改路径,比如遗漏一个字符,那么它不是有效路径,也不会抛出错误!所以我不知道什么有效,什么无效。
有没有办法知道变量 db 是否连接到数据库? 有什么方法可以知道 Database.forURL 成功还是失败了??
我怀疑您看不到结果的原因只是您的主程序在查询完成之前完成了。
我的意思是,db.run(action)
的类型将是 Future[Seq[Int]]
。调用 foreach
不会阻塞结果。 foreach
在 Future
上的行为在此处记录:
It is important to note that calling the foreach combinator does not block to traverse the value once it becomes available. Instead, the function for the foreach gets asynchronously executed only if the future is completed successfully. -- http://docs.scala-lang.org/overviews/core/futures.html
所以你能做的就是等待结果:
import scala.concurrent.Await
import scala.concurrent.duration._
val result = Await.result(db.run(action), 2 seconds)
result.foreach(println)
...这将确保您在程序终止之前看到打印的结果。
关于连接到数据库的错误...
- 在
forUrl
中,如果连接字符串不是有效的识别方案,您将看到一个异常,例如java.sql.SQLException: No suitable driver
- 如果您提供了有效的 URL,但数据库名称错误,这将取决于所讨论的数据库。对于 H2,我怀疑是 SQLite,您可能会创建一个新的空数据库。您可以在 JDBC URL 中传递一些参数来控制此行为,但这将是 driver/database 特定的。