保持数据库会话打开

时间:2013-06-04 18:37:23

标签: scala slick

我正在尝试利用TypeSafe的光滑库与MySQL服务器连接。所有的启动/教程示例都使用withSession{},框架将自动创建会话,在{}内执行查询,然后在块结束时终止会话。

我的程序相当繁琐,我希望在整个脚本执行过程中保持持久的连接。到目前为止,我已拼凑此代码以显式创建和关闭会话。

val db = Database.forURL("jdbc:mysql://localhost/sandbox", user = "root", password="***", driver = "com.mysql.jdbc.Driver")
val s = db.createSession()
...
s.close()

我可以在哪里执行查询。但是,当我尝试执行命令时,例如

  

(Q.u +“插入TEST(名称)值('”+ name +“')”)。执行

崩溃是因为找不到隐式会话。我不完全理解syntax of the execute definition in the documentation,但似乎可能有一个可选参数来传递显式会话。我已经尝试过使用.execute(s),但这会发出一个警告:(s)在纯粹的探索中没有做任何事情。

如何显式指定预先存在的会话以运行查询?

附加: JAB解决方案的试用代码

class ActorMinion(name: String) extends Actor
{
    Database.forURL("jdbc:mysql://localhost/sandbox", user = "root", password="****", driver = "com.mysql.jdbc.Driver") withSession
    {
        def receive =
        {
            case Execute =>
            {
                (Q.u + "insert into TEST (name) values('"+name+"')").execute

                sender ! DoneExecuting(name,output,err.toString)
            }
        }
    }
}

返回编译错误

  

[错误] /home/ubuntu/helloworld/src/main/scala/hw.scala:41:扩展功能缺少参数类型

     

[error]必须完全知道匿名函数的参数类型。 (SLS 8.5)

     

[错误]预期的类型是:?

     

[错误] {

     

[错误] ^

     

[错误]发现一个错误

2 个答案:

答案 0 :(得分:8)

我能从this answer

中得到我需要的东西
//imports at top of file
//import Database.threadLocalSession <--this should be commented/removed
import scala.slick.session.Session // <-- this should be added
......
//These two lines in actor constructor
val db = Database.forURL("jdbc:mysql://localhost/sandbox", user = "root", password="****", driver = "com.mysql.jdbc.Driver")
implicit var session: Session = db.createSession()
......
session.close() //This line in actor destructor

答案 1 :(得分:2)

只需在withSession{}中附上脚本的相关部分即可。请注意,如果您保持会话打开一段时间/正在执行大量数据库操作查询,您还应该考虑利用事务。

如果数据具有可能的外部源,那么您应该使用预准备语句进行插入。