Xamarin 将数据从服务器插入SQLite数据库

Xamarin 将数据从服务器插入SQLite数据库,xamarin,xamarin.forms,Xamarin,Xamarin.forms,我正在从服务器向SQLite数据库插入3000多个数据。问题是插入过程非常慢。是否有更好的方法来高效地插入数据?我所做的是将从服务器获取的数据转换为JSON对象,然后逐个插入。我知道我所做的是低效的。我怎样才能解决这个问题 public class AndroidSQLiteDb : ISQLiteDB { public SQLiteAsyncConnection GetConnection() { var dbFileName = "backend.db3";

我正在从服务器向SQLite数据库插入3000多个数据。问题是插入过程非常慢。是否有更好的方法来高效地插入数据?我所做的是将从服务器获取的数据转换为JSON对象,然后逐个插入。我知道我所做的是低效的。我怎样才能解决这个问题

public class AndroidSQLiteDb : ISQLiteDB
{
    public SQLiteAsyncConnection GetConnection()
    {
        var dbFileName = "backend.db3";
        var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
        var path = Path.Combine(documentsPath, dbFileName);

        return new SQLiteAsyncConnection(path);
    }
}

public async void FirstSyncContacts(string host, string database, string contact)
    {
        try
        {
            var db = DependencyService.Get<ISQLiteDB>();
            var conn = db.GetConnection();

            var sql = "SELECT * FROM tblContacts WHERE Coordinator = '" + contact + "'";
            var getContacts = conn.QueryAsync<ContactsTable>(sql);
            var resultCount = getContacts.Result.Count;
            var current_datetime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:00");

            //Check if the retailer has been sync
            if (resultCount < 1)
            {
                try
                {
                    syncStatus.Text = "Syncing Retailer";

                    var link = Constants.requestUrl + "Host=" + host + "&Database=" + database + "&Contact=" + contact + "&Request=9DpndD";
                    string contentType = "application/json";
                    JObject json = new JObject
                    {
                        { "ContactID", contact }
                    };

                    HttpClient client = new HttpClient();
                    var response = await client.PostAsync(link, new StringContent(json.ToString(), Encoding.UTF8, contentType));

                    if (response.IsSuccessStatusCode)
                    {
                        var content = await response.Content.ReadAsStringAsync();

                        if (content != "")
                        {
                            var contactsresult = JsonConvert.DeserializeObject<List<ContactsData>>(content);

                            foreach (var item in contactsresult)
                            {
                                // update only the properties that you have to...

                                item.LastSync = Convert.ToDateTime(current_datetime);
                                item.ServerUpdate = Convert.ToDateTime(item.ServerUpdate);
                                item.MobileUpdate = Convert.ToDateTime(item.MobileUpdate);
                            }
                            await conn.InsertAsync(contactsresult);

                        }
                    }

                    //Proceed to next function
                    FirstSyncRetailerGroup(host, database, contact);
                }
                catch (Exception ex)
                {
                    Console.Write("Syncing Retailer Error " + ex.Message);
                }
            }
            //If not get the retailer
            else
            {
                SyncContacts(host, database, contact);
            }
        }
        catch (Exception ex)
        {
            Console.Write("Syncing Retailer Error " + ex.Message);
        }
    }
在一个后台线程中使用非异步插入,而不是3000个单独的异步调用

重新使用反序列化对象步骤中的列表,而不是创建新的本地对象,这些对象将在每次循环迭代中被丢弃

无需将所有这些json属性item.XXX分配给另一个局部变量,只需根据需要更新每个现有ContactsData的属性,然后再将其插入数据库

使用SQLiteConnection的示例:
在一个后台线程中使用非异步插入,而不是3000个单独的异步调用。。。创建一个ContactsTable实例并重用重置/设置所有属性。在每次插入循环迭代中,它将节省大量GC时间,无需将所有这些json属性item.XXX分配给另一个局部变量,只是为了将它们重新分配到ContactsTable的属性。@SushiHangover你能告诉我怎么做吗?@SushiHangover我真的需要help@LawrenceAgulto请避免在sqlite中使用json。SQLite仅用于内部用途。因此,您可以在没有JSON的情况下进行管理。如果你避开这个,你可以看到速度difference@RanjithKumar我怎样才能避免这种情况?你能告诉我怎么做吗?我正在使用我的代码将数据从我的服务器同步到我的sqlite数据库中,我还能使用var db=DependencyService.Get;var conn=db.GetConnection;依赖服务?是的,只需添加另一个返回非异步连接的Get…您可以根据我的代码显示完整的代码吗?我很困惑我的完整代码?该代码是基于您的代码直接写入Stackoverflow的,我的意思是您可以修改这个var conn=new-SQLiteConnectiondbPath,true,null;并使用var db=DependencyService.Get;var conn=db.GetConnection;
// Use the non-async version of SQLiteConnection
var conn = new SQLiteConnection(dbPath, true, null);

// code removed for example...

await System.Threading.Tasks.Task.Run(() =>
{
    var contactsresult = JsonConvert.DeserializeObject<List<ContactsData>>(content);

    // start a transaction block so all 3000 records are committed at once.
    conn.BeginTransaction();

    // Use `foreach` in order shortcut the need to retrieve the object from the list via its index
    foreach (var item in contactsresult)
    {
        // update only the properties that you have to...

        item.LastSync = Convert.ToDateTime(current_datetime);
        item.ServerUpdate = Convert.ToDateTime(item.ServerUpdate);
        item.MobileUpdate = Convert.ToDateTime(item.MobileUpdate);

        conn.Insert(item);
    }
    conn.Commit();
});
var db = DependencyService.Get<ISQLiteDB>();
var conn = db.GetConnection();

~~~

var contactsresult = JsonConvert.DeserializeObject<List<ContactsData>>(content);

foreach (var item in contactsresult)
{
    // update only the properties that you have to...

    item.LastSync = Convert.ToDateTime(current_datetime);
    item.ServerUpdate = Convert.ToDateTime(item.ServerUpdate);
    item.MobileUpdate = Convert.ToDateTime(item.MobileUpdate);
}
conn.InsertAsync(contactsresult); // Insert the entire list at once...