我如何可靠地在SQLite中检查特定的用户表是否存在?
我并不是要求使用不可靠的方法,比如检查表上的“select *”是否返回错误(这是一个好主意吗?)
原因如下:
在我的程序中,我需要创建并填充一些表,如果它们还不存在的话。
如果它们已经存在,我需要更新一些表。
我是否应该采取其他路径来表示已经创建了相关的表-例如,通过在磁盘上的程序初始化/设置文件中创建/放置/设置某个标志?
或者我的方法有意义吗?
我如何可靠地在SQLite中检查特定的用户表是否存在?
我并不是要求使用不可靠的方法,比如检查表上的“select *”是否返回错误(这是一个好主意吗?)
原因如下:
在我的程序中,我需要创建并填充一些表,如果它们还不存在的话。
如果它们已经存在,我需要更新一些表。
我是否应该采取其他路径来表示已经创建了相关的表-例如,通过在磁盘上的程序初始化/设置文件中创建/放置/设置某个标志?
或者我的方法有意义吗?
当前回答
Use
SELECT 1 FROM table LIMIT 1;
防止所有记录被读取。
其他回答
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
参见(7)如何在SQLite FAQ中列出SQLite数据库中包含的所有表/索引:
SELECT name FROM sqlite_master
WHERE type='table'
ORDER BY name;
如果你处理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()
你可以试试:
SELECT name FROM sqlite_master WHERE name='table_name'
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;}