【问题标题】:Getting metadata in plain SQL statement in Slick 3.1.x在 Slick 3.1.x 中以普通 SQL 语句获取元数据
【发布时间】:2016-06-17 11:44:06
【问题描述】:

在 Slick 中的以下普通 SQL 语句中,我事先知道它将返回 (String, String) 的列表

sql"""select c.name, s.name
      from coffees c, suppliers s
      where c.price < $price and s.id = c.sup_id""".as[(String, String)]

但是如果我不知道列类型怎么办?我可以分析元数据并检索值吗?在 JDBC 中我可以使用 getInt(n) 和 getString(n),在 Slick 中是否有类似的东西?

【问题讨论】:

    标签: slick slick-3.0


    【解决方案1】:

    你可以使用tsql (Type-Checked SQL Statements):

    tsql"""select c.name, s.name
          from coffees c, suppliers s
          where c.price < $price and s.id = c.sup_id"""
    

    这将返回一个DBIO[Seq[(String, String)]](取决于列类型)。

    无需调用.as即可生成正确类型的DBIOAction

    注意:我发现它在选项类型上有点不稳定(到了无法使用的地步),所以要注意你的列是否可以是 null(自 null: String 起)。

    这需要一些连接,你需要@StaticDatabaseConfig(例如在你的 DAO 上),因为这些类型是在编译时针对数据库检查的:

    # annotate the object
    @StaticDatabaseConfig("file:src/main/resources/application.conf#tsql")
    ...
    
        val dc = DatabaseConfig.forAnnotation[JdbcProfile]
        import dc.driver.api._
        val db = dc.db
    
        # to pull out a Future[Seq[String, String]]
        # use db.run(tsql"...")
        # to pull out a Future[Option[(String, String)]]
        # use db.run(tsql"...".headOption)
        # etc.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-28
      • 1970-01-01
      • 2016-01-12
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 2019-07-26
      相关资源
      最近更新 更多