Windows Phone 8 从 json 数组优化插入到 sqlite table

Windows Phone 8 optimized insertion into sqlite table from json array

我的 Windows Phone 8 应用正在从服务器下载 json 格式的项目列表:

{
  "error":false,
  "lists":[{
    "code":1,
    "name":"item 1"
  },{
    "code":2,
    "name":"item 2"
  },{ 
  ... 
  },{
    "code":100000,
    "name":"item 100000"
  }]
}

请注意,我的应用正在下载 100.000 个项目。

然后我的应用程序解码 json 并迭代每个项目,以便将其插入到移动应用程序 SQLite 数据库中:

JObject content = JObject.Parse(result);
string jsonLists = content.GetValue("lists").ToString().Trim();
JArray jarrTAR = JArray.Parse(jsonLists);

foreach (JObject content2 in jarrTAR.Children<JObject>())
{
    string code = content2.GetValue("code").ToString().Trim();
    string name = content2.GetValue("name").ToString().Trim();
    ...
    using (var db = new SQLiteConnection(MainPage.DBPath))
    {
        db.RunInTransaction(() =>
        {
            db.Insert(new Table1()
            {
                Code = code,
                Name = name,
                ...
            });
        });
     }
}  

这行得通,但是将 100.000 个项目插入数据库需要 10 多分钟。

我认为这种方法(将项目一个接一个地插入table)可能会接受table一些项目下载,但是推荐的插入项目的策略应该是什么时候他们的数量大约是100.000?

有什么方法可以在一个查询中插入所有项目以优化插入时间?

大部分时间可能花在 opening/closing 数据库连接上,因为您要为每个项目创建新连接,然后 "running in transaction" 一次创建一个项目。

您应该先创建例如您要插入的 List 个对象,然后将所有项目插入事务中。说...

db.RunInTransaction(() => db.InsertAll(items));

您也可以使用 async/await 和 运行 此操作作为新的 Task

private async void SomeMethodHere()
{
    ...

    var myItems = new List<Table1>();
    foreach (JObject content2 in jarrTAR.Children<JObject>())
    {
        // create and/or populate collection here
    }

    await InsertAsync("my.sqlite.path", myItems);
}

public Task InsertAsync(string dbPath, IEnumerable<Table1> items)
{
    return Task.Run(() =>
        {
            using (var connection = new SQLiteConnection(dbPath))
                connection.RunInTransaction(() => connection.InsertAll(items));
        });
}