是否可以检查SQLite表是否存在。

时间:2016-10-07 14:32:15

标签: 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();
        }

从我所看到的应用程序正在使用SQLite-net

我想知道的是,如果有一种方法可以检查表是否存在而不是这样做,无论如何都要尝试创建它,然后尝试检查它是否有行。

3 个答案:

答案 0 :(得分:9)

此查询将返回数据库中的表列表

SELECT * FROM sqlite_master WHERE type = 'table';

您可以将其过滤到单行以进行“存在”检查。

SELECT * FROM sqlite_master WHERE type = 'table' AND tbl_name = 'xyz';

答案 1 :(得分:7)

您可以这样做:

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;
}

Source

答案 2 :(得分:2)

您可以使用以下代码

public bool IsTableExists(string tableName)
        {
            try
            {
                var tableInfo = database.GetConnection().GetTableInfo(tableName);
                if(tableInfo.Count > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }


public SQLiteAsyncConnection database;

        public ClientDatabase(string dbPath)
        {
            database = new SQLiteAsyncConnection(dbPath);

        }
相关问题