Ala*_*an2 2 sqlite xamarin xamarin.forms
我有以下代码:
dbcon = DependencyService.Get<ISQLite>().GetConnection();
// create the tables
dbcon.CreateTable<Category>();
dbcon.CreateTable<Settings>();
var settings = dbcon.Table<Settings>().ToList();
if (settings.Count <= 0)
{
var noa = new Settings { Setting = "NumberOfAnswers", Value = 5 };
var cfs = new Settings { Setting = "CardFrontSide", Value = 0 };
dbcon.Insert(noa);
dbcon.Insert(cfs);
}
var categories = dbcon.Table<Category>().ToList();
if (categories.Count <= 0)
{
InsertCategory();
}
Run Code Online (Sandbox Code Playgroud)
从我所看到的应用程序是使用SQLite-net
我想知道的是,如果有一种方法可以检查表是否存在而不是这样做,无论如何都要尝试创建它,然后尝试检查它是否有行.
此查询将返回数据库中的表列表
SELECT * FROM sqlite_master WHERE type = 'table';
Run Code Online (Sandbox Code Playgroud)
您可以将其过滤到单行以进行"存在"检查.
SELECT * FROM sqlite_master WHERE type = 'table' AND tbl_name = 'xyz';
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
public static bool TableExists<T> (SQLiteConnection connection)
{
const string cmdText = "SELECT name FROM sqlite_master WHERE type='table' AND name=?";
var cmd = connection.CreateCommand (cmdText, typeof(T).Name);
return cmd.ExecuteScalar<string> () != null;
}
Run Code Online (Sandbox Code Playgroud)