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

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

原因如下:

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

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

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

或者我的方法有意义吗?


当前回答

如果你得到一个"table already exists"错误,在SQL字符串中做如下修改:

CREATE table IF NOT EXISTS table_name (para1,para2);

这样可以避免异常。

其他回答

如果你处理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()

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

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

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

我想我要对这个讨论发表我的意见,即使这是一个相当老的问题。 如果表存在,该查询返回标量1,否则返回0。

select 
    case when exists 
        (select 1 from sqlite_master WHERE type='table' and name = 'your_table') 
        then 1 
        else 0 
    end as TableExists

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