Reputation:
So the documentation for Typesafe's Slick is very thin and its examples are for Play which doesn't help very much working in Eclipse.
I try to connect to an existing SQLite database on my system, which consists of one 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)
}
}
Starting the program doesn't give me any result though. Also if i change the path, like leaving out a character, so it is not a valid path, doesn't throw an error! So i don't have a clue what is working and what is not working.
Is there a way of knowing , if variable db is connected to a database? Any way of knowing that Database.forURL worked or failed??
Upvotes: 0
Views: 1219
Reputation: 4320
I suspect the reason you see no result is just that your main program is completing before the query has completed.
What I mean is, the type of db.run(action)
will be Future[Seq[Int]]
. Calling foreach
on that does not block for a result. The behaviour of foreach
on a Future
is noted here:
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
So what you can do is await the result:
import scala.concurrent.Await
import scala.concurrent.duration._
val result = Await.result(db.run(action), 2 seconds)
result.foreach(println)
...which will ensure you see the result printed before your program terminates.
In terms of errors connecting to a database...
forUrl
, if the connection string is not a valid recognized scheme, you'll see an exception such as java.sql.SQLException: No suitable driver
Upvotes: 3