如何在db-sqlite-xamariniOS中检查表的存在

本文关键字:检查表 存在 db-sqlite-xamariniOS | 更新日期: 2023-09-27 18:20:01

如何检查表是否在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。
@提前谢谢。

如何在db-sqlite-xamariniOS中检查表的存在

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

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

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

顺便提一下,低t的桌子;)

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