我如何可靠地在SQLite中检查特定的用户表是否存在?
我并不是要求使用不可靠的方法,比如检查表上的“select *”是否返回错误(这是一个好主意吗?)
原因如下:
在我的程序中,我需要创建并填充一些表,如果它们还不存在的话。
如果它们已经存在,我需要更新一些表。
我是否应该采取其他路径来表示已经创建了相关的表-例如,通过在磁盘上的程序初始化/设置文件中创建/放置/设置某个标志?
或者我的方法有意义吗?
我如何可靠地在SQLite中检查特定的用户表是否存在?
我并不是要求使用不可靠的方法,比如检查表上的“select *”是否返回错误(这是一个好主意吗?)
原因如下:
在我的程序中,我需要创建并填充一些表,如果它们还不存在的话。
如果它们已经存在,我需要更新一些表。
我是否应该采取其他路径来表示已经创建了相关的表-例如,通过在磁盘上的程序初始化/设置文件中创建/放置/设置某个标志?
或者我的方法有意义吗?
当前回答
我现在在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);
}
其他回答
这是我的SQLite Cordova代码:
get_columnNames('LastUpdate', function (data) {
if (data.length > 0) { // In data you also have columnNames
console.log("Table full");
}
else {
console.log("Table empty");
}
});
另一个是:
function get_columnNames(tableName, callback) {
myDb.transaction(function (transaction) {
var query_exec = "SELECT name, sql FROM sqlite_master WHERE type='table' AND name ='" + tableName + "'";
transaction.executeSql(query_exec, [], function (tx, results) {
var columnNames = [];
var len = results.rows.length;
if (len>0){
var columnParts = results.rows.item(0).sql.replace(/^[^\(]+\(([^\)]+)\)/g, '$1').split(','); ///// RegEx
for (i in columnParts) {
if (typeof columnParts[i] === 'string')
columnNames.push(columnParts[i].split(" ")[0]);
};
callback(columnNames);
}
else callback(columnNames);
});
});
}
我想我要对这个讨论发表我的意见,即使这是一个相当老的问题。 如果表存在,该查询返回标量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
参见(7)如何在SQLite FAQ中列出SQLite数据库中包含的所有表/索引:
SELECT name FROM sqlite_master
WHERE type='table'
ORDER BY name;
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
你可以使用一个简单的方法,我在c#和Xamarin中使用这个方法,
public class LoginService : ILoginService
{
private SQLiteConnection dbconn;
}
在登录服务类中,我有许多方法用于访问sqlite中的数据,我将数据存储到一个表中,并将登录页面 它只在用户未登录时显示。
为了这个目的,我只需要知道表是否存在,在这种情况下,如果它存在,那是因为它有数据
public int ExisteSesion()
{
var rs = dbconn.GetTableInfo("Sesion");
return rs.Count;
}
如果表不存在,它只返回0,如果表存在,那是因为它有数据,它返回它的总行数。
在模型中,我指定了表必须接收的名称,以确保其正确操作。
[Table("Sesion")]
public class Sesion
{
[PrimaryKey]
public int Id { get; set; }
public string Token { get; set; }
public string Usuario { get; set; }
}