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);

  

猜你喜欢

转载自www.cnblogs.com/jiecaoge/p/10045523.html
今日推荐