我如何可靠地在SQLite中检查特定的用户表是否存在?

我并不是要求使用不可靠的方法,比如检查表上的“select *”是否返回错误(这是一个好主意吗?)

原因如下:

在我的程序中,我需要创建并填充一些表,如果它们还不存在的话。

如果它们已经存在,我需要更新一些表。

我是否应该采取其他路径来表示已经创建了相关的表-例如,通过在磁盘上的程序初始化/设置文件中创建/放置/设置某个标志?

或者我的方法有意义吗?


当前回答

一种变体是使用SELECT COUNT(*)而不是SELECT NAME,即。

SELECT count(*) FROM sqlite_master WHERE type='table' AND name='table_name';

如果表不存在,返回0,如果存在,返回1。这可能在你的编程中很有用,因为数值结果处理起来更快/更容易。下面说明了如何在Android中使用SQLiteDatabase, Cursor, rawQuery带参数来做到这一点。

boolean tableExists(SQLiteDatabase db, String tableName)
{
    if (tableName == null || db == null || !db.isOpen())
    {
        return false;
    }
    Cursor cursor = db.rawQuery(
       "SELECT COUNT(*) FROM sqlite_master WHERE type = ? AND name = ?",
       new String[] {"table", tableName}
    );
    if (!cursor.moveToFirst())
    {
        cursor.close();
        return false;
    }
    int count = cursor.getInt(0);
    cursor.close();
    return count > 0;
}

其他回答

Use:

PRAGMA table_info(your_table_name)

如果结果表为空,则your_table_name不存在。

文档:

编译指示schema.table_info(表名); 这个pragma为命名表中的每一列返回一行。结果集中的列包括列名、数据类型、列是否可以为NULL以及列的默认值。对于不属于主键的列,结果集中的“pk”列为零;对于属于主键的列,结果集中的“pk”列是主键中的列的索引。 在table_info pragma中命名的表也可以是视图。

示例输出:

cid|name|type|notnull|dflt_value|pk
0|id|INTEGER|0||1
1|json|JSON|0||0
2|name|TEXT|0||0

R DBI包中的函数dbExistsTable()为R程序员简化了这个问题。请看下面的例子:

library(DBI)
con <- dbConnect(RSQLite::SQLite(), ":memory:")
# let us check if table iris exists in the database
dbExistsTable(con, "iris")
### returns FALSE

# now let us create the table iris below,
dbCreateTable(con, "iris", iris)
# Again let us check if the table iris exists in the database,
dbExistsTable(con, "iris")
### returns TRUE 

我喜欢的方法是:

SELECT "name" FROM pragma_table_info("table_name") LIMIT 1;

如果您得到一个行结果,则该表存在。这是更好的(对我),然后检查sqlite_master,因为它也将检查附加和临时数据库。

使用以下代码:

SELECT name FROM sqlite_master WHERE type='table' AND name='yourTableName';

如果返回的数组count等于1,则表示该表存在。否则它就不存在。

参见(7)如何在SQLite FAQ中列出SQLite数据库中包含的所有表/索引:

SELECT name FROM sqlite_master
WHERE type='table'
ORDER BY name;