【问题标题】:How to create and populate a local SQLite db with API json data?如何使用 API json 数据创建和填充本地 SQLite 数据库?
【发布时间】:2020-05-20 13:47:44
【问题描述】:

我正在创建一个Xamarin.Forms 应用程序,它将使用我在 C# 中创建的 API Rest 中的数据。

我要做的是将所有从API 返回的JSON 数据存储到本地SQLite DB,然后我将在所有应用程序接口中使用该数据。

到这里一切都好:

public async void GetProduct()
    {
        var httpClient = new HttpClient();
        var response = await httpClient.GetStringAsync("localhost/api/products");
        var product = JsonConvert.DeserializeObject<List<Product>>(response);

        lvProducts.ItemsSource = propriedade;

    }

我想要的是在本地数据库中填充一个表,而不是填充一个ListView

你有一些简单的可实现代码可以用来实现这个目标吗?

【问题讨论】:

标签: sqlite xamarin.forms xamarin.android


【解决方案1】:

如果您只想存储数据并显示它(正如您的帖子所暗示的那样),那么您应该使用 monkey-cache 来完成繁重的工作。它是专门为解决这个问题而设计的。

否则,您需要考虑实现本地数据访问并编写自己的数据访问代码。 This link 将帮助您开始。

【讨论】:

    【解决方案2】:

    我想要的是在本地数据库中填充一个表,而不是填充一个 ListView。

    根据您的描述,您已经使用 Api 获得了 List,现在您要创建本地 sqlite 表并将此列表填充到此表中。

    首先需要通过Nuget包安装sqlite-net-pcl

    然后使用以下代码创建一个 sqlite 数据库和产品表:

     public void createtable()
        {
            var fileName = "Productdata.db3";
            var documentPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            var path = Path.Combine(documentPath, fileName);
    
            connection = new SQLiteConnection(path);
            connection.CreateTable<Product>();
    
    
        }
    

    最后foreach List数据,并在Sqlite Product Table中插入数据。

     private void Btn4_Clicked(object sender, EventArgs e)
        {
            var products = JsonConvert.DeserializeObject<List<Product>>(response);
            foreach(Product p in products)
            {
                Product prod = new Product();
                prod.productname = p.productname;
                var data = connection.Table<Product>();
    
                var d1 = data.Where(x => x.productname == prod.productname).FirstOrDefault();
                if (d1 == null)
                {
                    connection.Insert(prod);
                    Console.WriteLine("Sucessfully Added");
                }
                else
                {
                    Console.WriteLine("Already Mail id Exist");
                }
            }
        }
    

    这是产品类别:

    public class Product
    {
        [PrimaryKey, AutoIncrement]
        public int Id { get; set; }
        public string productname { get; set; }
    
    }
    

    这里是关于在本地sqlite数据库中插入数据的文章,你可以看看:

    https://www.c-sharpcorner.com/article/working-with-sqlite-in-xamarine-forms-application/

    【讨论】:

      猜你喜欢
      • 2011-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多