1. 程式人生 > >xamarin.form使用sqlite

xamarin.form使用sqlite

在專案裡引用sqlite-net-pcl這個nuget包

每個平臺都有自己的資料庫存放位置,需要單獨獲取

public interface ISQLiteFolder
    {
        string GetSQLiteDocumentPath();
    }

  然後在Android平臺新增實現類

[assembly: Xamarin.Forms.Dependency(typeof(Folder))]
namespace App1.Droid
{
    public class Folder : ISQLiteFolder
    {
        public string GetSQLiteDocumentPath()
        {
            return Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        }
    }
}

  然後在IOS平臺新增實現類

[assembly: Xamarin.Forms.Dependency(typeof(Folder))]
namespace App1.iOS
{
    public class Folder : ISQLiteFolder
    {
        public string GetSQLiteDocumentPath()
        {
            return Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        }
    }
}

  然後在PCL中使用以下程式碼,就可以呼叫對應平臺的獲取路徑的方法了

            string databasePath = DependencyService.Get<ISQLiteFolder>().GetSQLiteDocumentPath();

  使用如下方法建立資料庫和其他操作

 List<Model> models = new List<Model>();
            models.Add(new Model() { ID = 1, Display = "display", Value = "value" });

            string databasePath = DependencyService.Get<ISQLiteFolder>().GetSQLiteDocumentPath();
            SQLite.SQLiteConnection con = new SQLite.SQLiteConnection(Path.Combine(databasePath, "local.db3"));
            if (con.ExecuteScalar<int>("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name=?", typeof(Model).Name) == 0)
            {
                con.CreateTable<Model>();
                con.InsertAll(models);
            }
            var model = con.Get<Model>(1); //根據id查詢
            con.Update(model);
            con.Delete(model);