如何检查db sqlite xamarin iOS中存在的表

时间:2014-08-30 12:05:58

标签: c# ios database sqlite xamarin

如何检查在 db 数据库中创建表的位置。

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!");
        }
 }

它总是给我数1 @thanks提前。

4 个答案:

答案 0 :(得分:13)

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

答案 1 :(得分:3)

为什么你需要count(),当然即使它存在,值必须为1, 我的建议是

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

顺便说一下t表;)

答案 2 :(得分:3)

扩大Jasons点。更通用的方法是:

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
}

答案 3 :(得分:0)

 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)
            {       
            }
        }