SLICK 3.0(Scala)查詢在多次運行之前不會返回數據(我認為) [英] Slick 3.0 (scala) queries don't return data till they are run multiple times (I think)

查看:0
本文介紹了SLICK 3.0(Scala)查詢在多次運行之前不會返回數據(我認為)的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

我對數據庫、SLICK和Scala非常(非常)陌生,所以我使用了他們在http://slick.typesafe.com/doc/3.0.0/gettingstarted.html

文檔中的示例代碼

我的問題是,由于某些原因,我必須多次運行查詢才能返回數據。在它返回結果之前,我必須至少重新運行3-4次。我使用for循環重新運行查詢,它們也不一定每次都給我完全相同的結果。

如下所示創建兩個表:

  class Patients(tag: Tag) extends Table[(String, String, Int, String)](tag, "Patientss") {
    def PID = column[String]("Patient Id", O.PrimaryKey)

    def Gender = column[String]("Gender")

    def Age = column[Int]("Age")

    def Ethnicity = column[String]("Ethnicity")

    def * = (PID, Gender, Age, Ethnicity)
  }

  val patientsss = TableQuery[Patients]

  class DrugEffect(tag: Tag) extends Table[(String, String, Double)](tag, "DrugEffectss") {

    def DrugID = column[String]("Drug ID", O.PrimaryKey)

    def PatientID = column[String]("Patient_ID")

    def DrugEffectssss = column[Double]("Drug Effect")

    def * = (DrugID, PatientID, DrugEffectssss)

    def Patient = foreignKey("Patient_FK", PatientID, patientsss)(_.PID)}

 val d_effects = TableQuery[DrugEffect]

然后我使用

創建這些表
  val create_empty = DBIO.seq((patientsss.schema ++ d_effects.schema).create)
  val setup_1 = db.run(create_empty)

我有兩個文本文件中的實際數據,我使用緩沖閱讀器對它們進行解析。 我將所有的藥物ID存儲在一個名為DrugIds

的列表中

然后,我開始按以下方式填表

我首先填寫患者表:

   while (switch != 1) {

    val Patient = CurPatient.split("\s+")

    if (Patient(2).toUpperCase() == "NA" || (Patient(2).toFloat % 1 != 0))
      age = -1
    else age = Patient(2).toInt

    val insertPatient: DBIO[Option[Int]] = patientsss ++= Seq(
      (Patient(0), Patient(1), age, Patient(3))
    )       

    var future = db.run(insertPatient)



    CurPatient = PatientReader.readLine()

    if (CurPatient == null)
      switch = 1 //switch to 1

  }

對于DrugEffect表,我執行以下操作:

 while (switch != 1) {

    val Effect = CurEffect.split("\s+")

    for (i <- 1 until DrugIds.size - 1) {
      if (Effect(i).toUpperCase() == "NA")
        d_ef = -1.00

      else d_ef = (Effect(i).toFloat).asInstanceOf[Double]


      val insertEffect: DBIO[Option[Int]] = d_effects ++= Seq(
        (DrugIds(i), Effect(0), d_ef)
      )
      var future2 = db.run(insertEffect)
    }


    CurEffect = EffectReader.readLine()

    if (CurEffect == null)
      switch = 1
  }

然后我使用以下代碼段運行查詢

val q1 = for {
    c <- patientsss
  } yield (c.PID, c.Gender, c.Age, c.Ethnicity)

  db.stream(q1.result).foreach(println)

這應該只給我提供患者表中的所有數據,但它不一定會這樣做。

有時,我會收到以下錯誤(但并非總是):

java.util.concurrent.RejectedExecutionException: Task slick.backend.DatabaseComponent$DatabaseDef$$anon$3@47089c2c rejected from java.util.concurrent.ThreadPoolExecutor@6453123[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 215]
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2048)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:821)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1372)
at scala.concurrent.impl.ExecutionContextImpl$$anon$1.execute(ExecutionContextImpl.scala:136)
at slick.backend.DatabaseComponent$DatabaseDef$class.scheduleSynchronousStreaming(DatabaseComponent.scala:253)
at slick.jdbc.JdbcBackend$DatabaseDef.scheduleSynchronousStreaming(JdbcBackend.scala:38)
at slick.backend.DatabaseComponent$BasicStreamingActionContext.restartStreaming(DatabaseComponent.scala:516)
at slick.backend.DatabaseComponent$BasicStreamingActionContext.request(DatabaseComponent.scala:531)
at slick.backend.DatabasePublisher$$anon$3$$anonfun$onNext$2.apply(DatabasePublisher.scala:50)
at slick.backend.DatabasePublisher$$anon$3$$anonfun$onNext$2.apply(DatabasePublisher.scala:49)
at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:32)
at scala.concurrent.impl.ExecutionContextImpl$AdaptedForkJoinTask.exec(ExecutionContextImpl.scala:121)
at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.pollAndExecAll(ForkJoinPool.java:1253)
at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1346)
at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)

如果我運行一個更復雜的查詢,我得到的數據與查詢的參數是準確的,但同樣的問題也會出現,即結果重復、不存在或不完整(當我多次重新運行查詢時)。

如果可以,就像我5歲一樣解釋,或者給我介紹一個可以幫助我解決這些問題的資源

編輯:

bjfletcher的回答起作用了(謝謝!),但現在我有另一個問題:

每隔一段時間,代碼就會失敗,并顯示錯誤:

    Exception in thread "main" org.h2.jdbc.JdbcSQLException: Table "Patientss" not found; SQL statement:
insert into "Patientss" ("Patient Id","Gender","Age","Ethnicity")  values (?,?,?,?) [42102-162]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:329)
    at org.h2.message.DbException.get(DbException.java:169)
    at org.h2.message.DbException.get(DbException.java:146)
    at org.h2.command.Parser.readTableOrView(Parser.java:4758)
    at org.h2.command.Parser.readTableOrView(Parser.java:4736)
    at org.h2.command.Parser.parseInsert(Parser.java:954)
    at org.h2.command.Parser.parsePrepared(Parser.java:375)
    at org.h2.command.Parser.parse(Parser.java:279)
    at org.h2.command.Parser.parse(Parser.java:251)
    at org.h2.command.Parser.prepareCommand(Parser.java:217)
    at org.h2.engine.Session.prepareLocal(Session.java:415)
    at org.h2.engine.Session.prepareCommand(Session.java:364)
    at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1121)
    at org.h2.jdbc.JdbcPreparedStatement.<init>(JdbcPreparedStatement.java:71)
    at org.h2.jdbc.JdbcConnection.prepareStatement(JdbcConnection.java:267)
    at slick.jdbc.JdbcBackend$SessionDef$class.prepareStatement(JdbcBackend.scala:252)
    at slick.jdbc.JdbcBackend$BaseSession.prepareStatement(JdbcBackend.scala:386)
    at slick.jdbc.JdbcBackend$SessionDef$class.withPreparedStatement(JdbcBackend.scala:301)
    at slick.jdbc.JdbcBackend$BaseSession.withPreparedStatement(JdbcBackend.scala:386)
    at slick.driver.JdbcInsertInvokerComponent$BaseInsertInvoker.preparedInsert(JdbcInsertInvokerComponent.scala:177)
    at slick.driver.JdbcInsertInvokerComponent$BaseInsertInvoker$$anonfun$internalInsertAll$1.apply(JdbcInsertInvokerComponent.scala:201)
    at slick.jdbc.JdbcBackend$BaseSession.withTransaction(JdbcBackend.scala:422)
    at slick.driver.JdbcInsertInvokerComponent$BaseInsertInvoker.internalInsertAll(JdbcInsertInvokerComponent.scala:198)
    at slick.driver.JdbcInsertInvokerComponent$BaseInsertInvoker.insertAll(JdbcInsertInvokerComponent.scala:194)
    at slick.driver.JdbcInsertInvokerComponent$InsertInvokerDef$class.$plus$plus$eq(JdbcInsertInvokerComponent.scala:73)
    at slick.driver.JdbcInsertInvokerComponent$BaseInsertInvoker.$plus$plus$eq(JdbcInsertInvokerComponent.scala:152)
    at slick.driver.JdbcActionComponent$InsertActionComposerImpl$$anonfun$$plus$plus$eq$1.apply(JdbcActionComponent.scala:459)
    at slick.driver.JdbcActionComponent$InsertActionComposerImpl$$anonfun$$plus$plus$eq$1.apply(JdbcActionComponent.scala:459)
    at slick.driver.JdbcActionComponent$InsertActionComposerImpl$$anon$8.run(JdbcActionComponent.scala:449)
    at slick.driver.JdbcActionComponent$InsertActionComposerImpl$$anon$8.run(JdbcActionComponent.scala:447)
    at slick.backend.DatabaseComponent$DatabaseDef$$anon$2.liftedTree1$1(DatabaseComponent.scala:231)
    at slick.backend.DatabaseComponent$DatabaseDef$$anon$2.run(DatabaseComponent.scala:231)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)

并不總是發生,但經常發生,我不知道這意味著什么

推薦答案

所有數據庫調用都將使用Futures立即返回,即使它們尚未完成操作。這是異步的,不是同步的。

您可以通過以下兩種方式之一更改代碼以適應Futures

  1. 您可以對所有數據庫調用使用Await.result,以在該點等待,直到它們完成,例如:Await.result(db.run(insertEffect), Duration.Inf)

  2. 您可以使用.map(或者.flatMap,如果您從內部使用另一個Future),以及您希望在DB操作完成時運行的代碼。例如:db.run(insertEffect).map(_ => ... do stuff... )

查看有關該異常的另一個堆棧溢出thread,并了解一些原因。

這篇關于SLICK 3.0(Scala)查詢在多次運行之前不會返回數據(我認為)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持IT屋!

查看全文
登錄 關閉
掃碼關注1秒登錄
發送“驗證碼”獲取 | 15天全站免登陸
亚洲AV无码国产精品