加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 保持数据库会话打开

发布时间:2020-12-16 08:59:53 所属栏目:安全 来源:网络整理
导读:我正在尝试利用TypeSafe的光滑库与 MySQL服务器进行交互.所有的gettingstarted / tutorial示例都使用withSession {},其中框架将自动创建会话,在{}内执行查询,然后在块结束时终止会话. 我的程序相当繁琐,我希望在整个脚本执行过程中保持持久的连接.到目前为止
我正在尝试利用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()

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

(Q.u + “insert into TEST (name) values(‘”+name+”‘)”).execute

它崩溃,因为它无法找到隐式会话.我不完全理解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)
            }
        }
    }
}

哪个返回编译错误

[error] /home/ubuntu/helloworld/src/main/scala/hw.scala:41: missing parameter type for expanded function

[error] The argument types of an anonymous function must be fully known. (SLS 8.5)

[error] Expected type was: ?

[error] {

[error] ^

[error] one error found

解决方法

我能够从 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读