scala – 保持数据库会话打开
我正在尝试利用TypeSafe的光滑库与
MySQL服务器进行交互.所有的gettingstarted / tutorial示例都使用withSession {},其中框架将自动创建会话,在{}内执行查询,然后在块结束时终止会话.
我的程序相当繁琐,我希望在整个脚本执行过程中保持持久的连接.到目前为止,我已拼凑此代码以显式创建和关闭会话. val db = Database.forURL("jdbc:mysql://localhost/sandbox",user = "root",password="***",driver = "com.mysql.jdbc.Driver") val s = db.createSession() ... s.close() 我可以在哪里执行查询.但是,当我尝试执行命令时,例如
它崩溃,因为它无法找到隐式会话.我不完全理解syntax of the execute definition in the documentation,但似乎可能有一个可选参数来传递显式会话.我已经尝试过使用.execute(s),但这会发出一个警告:(s)在纯粹的尝试中没有做任何事情. 如何显式指定预先存在的会话以运行查询? 附:JAB解决方案的试用代码 class ActorMinion(name: String) extends Actor { Database.forURL("jdbc:mysql://localhost/sandbox",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) } } } } 哪个返回编译错误
解决方法
我能够从
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",driver = "com.mysql.jdbc.Driver") implicit var session: Session = db.createSession() ...... session.close() //This line in actor destructor (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |