简体   繁体   中英

Adding tables to SQLite database using Slick and Scala

So I have SQLite database using Slick and I want to add and remove tables from it. Here is what I have now:

Here is the database element class:

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)
}

I need to be able to create multiple tables using the class above. Something like this:

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

Problem is that I cant create new table because one already exists with name "myDB". I tried to add a parameter for the name of the Table in the class Data like so:

class Data(tag: Tag,tableName:String)

But then I couldn't create a table at all and got an error

unspecified value parameter tableName

And how can I query a specific table from the database given the table name? I tried to Implement this using Map with table name pointing to a table, but it doesnt work because the Map is not saved anywhere and is reset everytime the program starts.

This is what I had for querying a table:

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

Any help is appreciated!

Thanks!

Definition

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

...

Usage

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM