how to check table exist in db sqlite xamarin iOS

我的未来我决定 提交于 2020-01-15 01:23:25

问题


How to check where table is created in db database or not.

var folder = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
        SQLiteConnection db = new SQLiteConnection (System.IO.Path.Combine (folder,"note.db"));
        try{
            var existTable = db.Query<TransationTable>("SELECT count(*) FROM sqlite_master WHERE type = 'Table' AND name = 'TransationTable' ");
            Console.WriteLine ("Count {0}",existTable.Count);
          if(existTable.Count == 0){
          tableview.Hidden = true;
          lbl_NotFound.Hidden = false;
        }
    else{
          tableview.Hidden = false;
          lbl_NotFound.Hidden = true;
    }

        }
        catch{
            Console.WriteLine ("Calling Excpetion!");
        }
 }

Its always gives me of count 1.
@thanks in advance.


回答1:


    var info = conn.GetTableInfo(tableName);
    if (!info.Any())
    {
        conn.CreateTable<T>();
    }



回答2:


why do you need count(), of course even if it exist, the value must be 1, my suggestion is

SELECT name FROM sqlite_master WHERE type='table' AND name='your table name'; 

table with low t by the way ;)




回答3:


To expand upon Jasons point. A better more generic way would be:

string tableName = typeof(Customer).Name;
var customAttributes = typeof(Customer).GetCustomAttributes(typeof(SQLite.Net.Attributes.TableAttribute),false);
if (customAttributes.Count() > 0)
{
    tableName = (customAttributes.First() as SQLite.Net.Attributes.TableAttribute).Name;
}
var info = database.Connection.GetTableInfo(tableName);
if (!info.Any())
{
   //do stuff
}



回答4:


 public MainPage()
        {
            InitializeComponent();

            conn = DependencyService.Get<ISQLite>().GetConnection();

            try
            {
                //Student is table name ,replace student with your table name
                var existTable = conn.Query<Student>("SELECT name FROM sqlite_master WHERE type='table' AND name='Student'; ");
                if ((existTable.Count > 0))
                {
                   //Write code if table exists 
                }
            }
            catch (Exception Ex)
            {       
            }
        }


来源:https://stackoverflow.com/questions/25582180/how-to-check-table-exist-in-db-sqlite-xamarin-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!