2014-08-30 93 views
3

如何檢查在哪個表中創建了db數據庫與否。如何檢查表中是否存在db sqlite xamarin iOS

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提前。

回答

3

爲什麼你需要COUNT(),當然,即使存在,其值必須是1, 我的建議是

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

表的方式低噸;)

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

大多數其他答案會返回一個行sqlite異常 – peterincumbria 2017-03-12 14:34:01

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 
}