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

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

原因如下:

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

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

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

或者我的方法有意义吗?


当前回答

如果表存在,则返回1;如果表不存在,则返回0。

SELECT CASE WHEN tbl_name = "name" THEN 1 ELSE 0 END FROM sqlite_master WHERE tbl_name = "name" AND type = "table"

其他回答

在swift的数据库中,表是否存在

func tableExists(_ tableName:String) -> Bool {
        sqlStatement = "SELECT name FROM sqlite_master WHERE type='table' AND name='\(tableName)'"
        if sqlite3_prepare_v2(database, sqlStatement,-1, &compiledStatement, nil) == SQLITE_OK {
            if sqlite3_step(compiledStatement) == SQLITE_ROW {
                return true
            }
            else {
                return false
            }
        }
        else {
            return false
        }
            sqlite3_finalize(compiledStatement)
    }

如果你处理Big Table,我用Python和Sqlite做了一个简单的hack,你可以用任何其他语言做出类似的想法

步骤1:不要在create table命令中使用(如果不存在)

您可能知道,如果您之前已经创建了这个表,并且想要重新创建它,那么运行这个命令将会有一个异常,但这将引导我们进入第二步。

步骤2:使用try和except(或其他语言的try和catch)来处理最后一个异常

在这里,如果您之前没有创建表,则try case将继续执行,但如果您已经创建了,则可以将do your process置于except case,您将知道您已经创建了表。

代码如下:

def create_table():
    con = sqlite3.connect("lists.db")
    cur = con.cursor()
    try:
        cur.execute('''CREATE TABLE UNSELECTED(
        ID INTEGER PRIMARY KEY)''')
        print('the table is created Now')

    except sqlite3.OperationalError:
        print('you already created the table before')
    con.commit()
    cur.close()

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

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

一种变体是使用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;
}

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