【问题标题】:Adding tables to SQLite database using Slick and Scala使用 Slick 和 Scala 将表添加到 SQLite 数据库
【发布时间】:2015-01-08 12:43:28
【问题描述】:

所以我有使用 Slick 的 SQLite 数据库,我想从中添加和删除表。 这是我现在拥有的:

这里是数据库元素类:

class Data(tag: Tag)
  extends Table[(Int, String)](tag, "myDB") {
  // This is the primary key column:
  def id = column[Int]("ID", O.PrimaryKey)
  def name = column[String]("NAME")
  // Every table needs a * projection with the same type as the table's type parameter
  def * : ProvenShape[(Int, String)] = (id, name)
}

我需要能够使用上面的类创建多个表。像这样的:

def addTable(name:String){
  db withSession { implicit session =>
    val newTable = TableQuery[Data]
    newTable.ddl.create
  }
}

问题是我无法创建新表,因为已经存在一个名为“myDB”的表。我尝试在 Data 类中为表的名称添加一个参数,如下所示:

class Data(tag: Tag,tableName:String)

但后来我根本无法创建表并出现错误

unspecified value parameter tableName

在给定表名的情况下,如何从数据库中查询特定表? 我尝试使用表名指向表的 Map 来实现这一点,但它不起作用,因为 Map 没有保存在任何地方,并且每次程序启动时都会重置。

这是我用来查询表的:

def getDataFromTable(tableName:String)
{
  var res = ""
  db withSession { implicit session =>
    tables(tableName) foreach{
      case (id,name)=>
        res += id + " " + name + " "
    }
  }
  res
}

感谢任何帮助!

谢谢!

【问题讨论】:

    标签: database sqlite scala slick


    【解决方案1】:

    定义

    class Data(tag: Tag, tableName: String)
      extends Table[(Int, String)](tag, tableName){
    
    ...
    

    用法

    (new TableQuery(Data(_,"table_1"))).ddl.create
    (new TableQuery(Data(_,"table_2"))).ddl.create
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-25
      相关资源
      最近更新 更多