簡體   English   中英

如何在 scalikejdbc 中存儲 LocalDate 類型?

[英]How to store a LocalDate type in scalikejdbc?

我想通過使用 DatePicker 將日期集存儲到數據庫中,但是當我編譯時出現此錯誤

value localDate is not a member of scalikejdbc.WrappedResultSet
[error]               rs.localDate("due"),

我似乎找不到scalikejdbc.WrappedResultSetto的任何成員來將 LocalDate 存儲在數據庫中,或者以任何方式對其進行轉換以使數據庫接受它。 當我嘗試將其存儲在def getAllTasksrs.localDate("due")行時,就會出現問題。 我設置了一個 localDate ,因為我只是不知道還要設置什么。 下面是我正在使用的代碼示例。

import scalafx.beans.property.{IntegerProperty, ObjectProperty, StringProperty}
import scalafx.collections.ObservableBuffer
import scala.util.{ Try, Success, Failure }
import ch.makery.address.util.DateUtil._
import ch.makery.address.util.Database
import java.time.format.DateTimeFormatter
import java.time.LocalDate
import scalikejdbc._

class Tasks (
    val priorityS: String, 
    val titleS: String, 
    val dueD: LocalDate
    ) {
    
    // Format dueD to "dd-MMM-yyyy" format in type String, for ease in displaying
    var formatDate  = DateFormater(dueD).asString

    def this()      = this(null, null, null)
    var priority    = StringProperty(priorityS)
    var title       = new StringProperty(titleS)
    var due         = StringProperty(formatDate)
    var description = new StringProperty("task description")
}

object Tasks extends Database{
    
    val tasksData = new ObservableBuffer[Tasks]()
    Database.setupDB()
    tasksData ++= Tasks.getAllTasks

    def getAllTasks : List[Tasks] = {
        DB readOnly { implicit session =>
            sql"select * from tasks".map(rs => Tasks(
                rs.string("priority"), 
                rs.string("title"),
                rs.localDate("due"), 
                rs.string("description")
            )).list.apply()
        }
    }
}

您沒有指定要使用的數據庫以及該數據庫中要存儲的數據的目標類型。 所以我的回答對此有一些假設。

讓我們定義我們自己的Binders實例。 假設您只想將其存儲為java.sql.Date ,您可以編寫如下內容:

import scalikejdbc._
import java.sql.{Date => SqlDate}

implicit val localDateBinder: Binders[LocalDate] = Binders.sqlDate.xmap(
  (sqlDate: SqlDate) => sqlDate.toLocalDate,
  (localDate: LocalDate) => SqlDate.valueOf(localDate)
)

或者如果它是一個String ,是這樣的:

import scalikejdbc._
import java.time.format.DateTimeFormatter

val dateFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern("dd-MM-YYYY")
implicit val localDateBinderString: Binders[LocalDate] = Binders.string.xmap(
  (stringDate: String) => LocalDate.parse(stringDate, dateFormatter),
  (localDate: LocalDate) => dateFormatter.format(localDate)
)

不過,您可能想要檢查null 就像它在新版本的庫中的完成方式一樣

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM