我怎么知道 ScalaQuery 中是否存在数据库表 [英] How could I know if a database table is exists in ScalaQuery

查看:33
本文介绍了我怎么知道 ScalaQuery 中是否存在数据库表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试 ScalaQuery,它真的很棒.我可以使用 Scala 类定义数据库表,并轻松查询.

I'm trying ScalaQuery, it is really amazing. I could defined the database table using Scala class, and query it easily.

但我想知道,在下面的代码中,我如何检查表是否存在,所以我不会两次调用Table.ddl.create"并在我运行该程序两次时得到异常?

But I would like to know, in the following code, how could I check if a table is exists, so I won't call 'Table.ddl.create' twice and get a exception when I run this program twice?

object Users extends Table[(Int, String, String)]("Users") {
    def id = column[Int]("id")
    def first = column[String]("first")
    def last = column[String]("last")
    def * = id ~ first ~ last
}

object Main
{
    val database = Database.forURL("jdbc:sqlite:sample.db", driver = "org.sqlite.JDBC")

    def main(args: Array[String]) {
        database withSession {
            // How could I know table Users is alrady in the DB?
            if ( ??? )  {
                Users.ddl.create
            }
        }
    }
}

推荐答案

ScalaQuery 0.9.4 版在 org.scalaquery.meta 包中包含了许多有用的 SQL 元数据包装类,例如 MTable:

ScalaQuery version 0.9.4 includes a number of helpful SQL metadata wrapper classes in the org.scalaquery.meta package, such as MTable:

http://scalaquery.org/doc/api/scalaquery-0.9.4/#org.scalaquery.meta.MTable

在 ScalaQuery 的测试代码中,我们可以看到使用这些类的示例.特别是,请参阅 org.scalaquery.test.MetaTest.

In the test code for ScalaQuery, we can see examples of these classes being used. In particular, see org.scalaquery.test.MetaTest.

我写了这个小函数来给我一张所有已知表的映射,以表名为键.

I wrote this little function to give me a map of all the known tables, keyed by table name.

import org.scalaquery.meta.{MTable}
def makeTableMap(dbsess: Session) : Map[String, MTable] = {
    val tableList = MTable.getTables.list()(dbsess);
    val tableMap = tableList.map{t => (t.name.name, t)}.toMap;
    tableMap;
}

现在,在创建 SQL 表之前,我可以检查if (!tableMap.contains(tableName))".

So now, before I create an SQL table, I can check "if (!tableMap.contains(tableName))".

这篇关于我怎么知道 ScalaQuery 中是否存在数据库表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆