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

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

原因如下:

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

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

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

或者我的方法有意义吗?


当前回答

在我看来,使用一个简单的SELECT查询是非常可靠的。最重要的是,它可以检查表是否存在于许多不同的数据库类型(SQLite / MySQL)。

SELECT 1 FROM table;

当您可以使用其他可靠的机制来确定查询是否成功时(例如,您可以通过Qt中的QSqlQuery查询数据库),这是有意义的。

其他回答

c++函数检查db和所有附加的数据库是否存在表和列(可选)。

bool exists(sqlite3 *db, string tbl, string col="1")
{
    sqlite3_stmt *stmt;
    bool b = sqlite3_prepare_v2(db, ("select "+col+" from "+tbl).c_str(),
    -1, &stmt, 0) == SQLITE_OK;
    sqlite3_finalize(stmt);
    return b;
}

编辑:最近发现了sqlite3_table_column_metadata函数。因此

bool exists(sqlite3* db,const char *tbl,const char *col=0)
{return sqlite3_table_column_metadata(db,0,tbl,col,0,0,0,0,0)==SQLITE_OK;}

Use

SELECT 1 FROM table LIMIT 1;

防止所有记录被读取。

参见(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;
}

我现在在c#中发现的最可靠的方法是使用最新的SQLite -net-pcl nuget包(1.5.231),它使用SQLite 3,如下所示:

var result = database.GetTableInfo(tableName);
if ((result == null) || (result.Count == 0))
{
    database.CreateTable<T>(CreateFlags.AllImplicit);
}