Insert data from server to SQLite Database












0















I am inserting 3000 plus data from my server to my SQLite Database. The problem is the inserting process is very slow. Is there a better way to insert the data efficiently and effectively? What I am doing is I converted the data I got from my server to JSON Object and insert it one-by-one. I know what I am doing is inefficient. How can I fix this?



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









share|improve this question

























  • Use the non-async Insert in one background thread, instead of 3000 separate async calls... create one instance of ContactsTable and reuse (reset/set all properties it on each insert loop iteration (will save a lot of GC time), no need to assign all those json properties (item.XXX) to another local variable, just to reassign them to the properties of the ContactsTable.

    – SushiHangover
    Nov 14 '18 at 3:44













  • @SushiHangover can you show me how?

    – Lawrence Agulto
    Nov 14 '18 at 3:45











  • @SushiHangover I really need help

    – Lawrence Agulto
    Nov 14 '18 at 3:50











  • @LawrenceAgulto please avoid json in sqlite. SQLite only for your internal purpose. So you can manage without JSON. If you avoid this you can see the speed difference

    – Ranjith Kumar
    Nov 14 '18 at 5:28











  • @RanjithKumar how can I avoid this? Can you show me how?

    – Lawrence Agulto
    Nov 14 '18 at 5:34
















0















I am inserting 3000 plus data from my server to my SQLite Database. The problem is the inserting process is very slow. Is there a better way to insert the data efficiently and effectively? What I am doing is I converted the data I got from my server to JSON Object and insert it one-by-one. I know what I am doing is inefficient. How can I fix this?



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









share|improve this question

























  • Use the non-async Insert in one background thread, instead of 3000 separate async calls... create one instance of ContactsTable and reuse (reset/set all properties it on each insert loop iteration (will save a lot of GC time), no need to assign all those json properties (item.XXX) to another local variable, just to reassign them to the properties of the ContactsTable.

    – SushiHangover
    Nov 14 '18 at 3:44













  • @SushiHangover can you show me how?

    – Lawrence Agulto
    Nov 14 '18 at 3:45











  • @SushiHangover I really need help

    – Lawrence Agulto
    Nov 14 '18 at 3:50











  • @LawrenceAgulto please avoid json in sqlite. SQLite only for your internal purpose. So you can manage without JSON. If you avoid this you can see the speed difference

    – Ranjith Kumar
    Nov 14 '18 at 5:28











  • @RanjithKumar how can I avoid this? Can you show me how?

    – Lawrence Agulto
    Nov 14 '18 at 5:34














0












0








0








I am inserting 3000 plus data from my server to my SQLite Database. The problem is the inserting process is very slow. Is there a better way to insert the data efficiently and effectively? What I am doing is I converted the data I got from my server to JSON Object and insert it one-by-one. I know what I am doing is inefficient. How can I fix this?



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









share|improve this question
















I am inserting 3000 plus data from my server to my SQLite Database. The problem is the inserting process is very slow. Is there a better way to insert the data efficiently and effectively? What I am doing is I converted the data I got from my server to JSON Object and insert it one-by-one. I know what I am doing is inefficient. How can I fix this?



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






xamarin xamarin.forms






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 14 '18 at 4:57







Lawrence Agulto

















asked Nov 14 '18 at 3:34









Lawrence AgultoLawrence Agulto

837




837













  • Use the non-async Insert in one background thread, instead of 3000 separate async calls... create one instance of ContactsTable and reuse (reset/set all properties it on each insert loop iteration (will save a lot of GC time), no need to assign all those json properties (item.XXX) to another local variable, just to reassign them to the properties of the ContactsTable.

    – SushiHangover
    Nov 14 '18 at 3:44













  • @SushiHangover can you show me how?

    – Lawrence Agulto
    Nov 14 '18 at 3:45











  • @SushiHangover I really need help

    – Lawrence Agulto
    Nov 14 '18 at 3:50











  • @LawrenceAgulto please avoid json in sqlite. SQLite only for your internal purpose. So you can manage without JSON. If you avoid this you can see the speed difference

    – Ranjith Kumar
    Nov 14 '18 at 5:28











  • @RanjithKumar how can I avoid this? Can you show me how?

    – Lawrence Agulto
    Nov 14 '18 at 5:34



















  • Use the non-async Insert in one background thread, instead of 3000 separate async calls... create one instance of ContactsTable and reuse (reset/set all properties it on each insert loop iteration (will save a lot of GC time), no need to assign all those json properties (item.XXX) to another local variable, just to reassign them to the properties of the ContactsTable.

    – SushiHangover
    Nov 14 '18 at 3:44













  • @SushiHangover can you show me how?

    – Lawrence Agulto
    Nov 14 '18 at 3:45











  • @SushiHangover I really need help

    – Lawrence Agulto
    Nov 14 '18 at 3:50











  • @LawrenceAgulto please avoid json in sqlite. SQLite only for your internal purpose. So you can manage without JSON. If you avoid this you can see the speed difference

    – Ranjith Kumar
    Nov 14 '18 at 5:28











  • @RanjithKumar how can I avoid this? Can you show me how?

    – Lawrence Agulto
    Nov 14 '18 at 5:34

















Use the non-async Insert in one background thread, instead of 3000 separate async calls... create one instance of ContactsTable and reuse (reset/set all properties it on each insert loop iteration (will save a lot of GC time), no need to assign all those json properties (item.XXX) to another local variable, just to reassign them to the properties of the ContactsTable.

– SushiHangover
Nov 14 '18 at 3:44







Use the non-async Insert in one background thread, instead of 3000 separate async calls... create one instance of ContactsTable and reuse (reset/set all properties it on each insert loop iteration (will save a lot of GC time), no need to assign all those json properties (item.XXX) to another local variable, just to reassign them to the properties of the ContactsTable.

– SushiHangover
Nov 14 '18 at 3:44















@SushiHangover can you show me how?

– Lawrence Agulto
Nov 14 '18 at 3:45





@SushiHangover can you show me how?

– Lawrence Agulto
Nov 14 '18 at 3:45













@SushiHangover I really need help

– Lawrence Agulto
Nov 14 '18 at 3:50





@SushiHangover I really need help

– Lawrence Agulto
Nov 14 '18 at 3:50













@LawrenceAgulto please avoid json in sqlite. SQLite only for your internal purpose. So you can manage without JSON. If you avoid this you can see the speed difference

– Ranjith Kumar
Nov 14 '18 at 5:28





@LawrenceAgulto please avoid json in sqlite. SQLite only for your internal purpose. So you can manage without JSON. If you avoid this you can see the speed difference

– Ranjith Kumar
Nov 14 '18 at 5:28













@RanjithKumar how can I avoid this? Can you show me how?

– Lawrence Agulto
Nov 14 '18 at 5:34





@RanjithKumar how can I avoid this? Can you show me how?

– Lawrence Agulto
Nov 14 '18 at 5:34












1 Answer
1






active

oldest

votes


















1















  1. Use the non-async Insert in one background thread, instead of 3000 separate async calls...


  2. Re-use the List from your DeserializeObject step instead of creating new local objects that will just be thrown away on each loop iteration.


  3. No need to assign all those json properties (item.XXX) to another local variable, just update the properties of each existing ContactsData as needed before inserting it into the DB.



Example using SQLiteConnection:



// 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();
});


Example using SQLiteAsyncConnection:



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...





share|improve this answer


























  • I am using my code to sync data from my server into my sqlite database can I still use var db = DependencyService.Get<ISQLiteDB>(); var conn = db.GetConnection();

    – Lawrence Agulto
    Nov 14 '18 at 4:18











  • DependencyService? yes, just add a another Get that returns the non-async connection....

    – SushiHangover
    Nov 14 '18 at 4:19











  • Can you show your complete code based on my code? I am so confused

    – Lawrence Agulto
    Nov 14 '18 at 4:21











  • My complete code? That code was written straight into Stackoverflow based upon your code

    – SushiHangover
    Nov 14 '18 at 4:22











  • I mean can you modify this var conn = new SQLiteConnection(dbPath, true, null); and use this var db = DependencyService.Get<ISQLiteDB>(); var conn = db.GetConnection();

    – Lawrence Agulto
    Nov 14 '18 at 4:25











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53292827%2finsert-data-from-server-to-sqlite-database%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1















  1. Use the non-async Insert in one background thread, instead of 3000 separate async calls...


  2. Re-use the List from your DeserializeObject step instead of creating new local objects that will just be thrown away on each loop iteration.


  3. No need to assign all those json properties (item.XXX) to another local variable, just update the properties of each existing ContactsData as needed before inserting it into the DB.



Example using SQLiteConnection:



// 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();
});


Example using SQLiteAsyncConnection:



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...





share|improve this answer


























  • I am using my code to sync data from my server into my sqlite database can I still use var db = DependencyService.Get<ISQLiteDB>(); var conn = db.GetConnection();

    – Lawrence Agulto
    Nov 14 '18 at 4:18











  • DependencyService? yes, just add a another Get that returns the non-async connection....

    – SushiHangover
    Nov 14 '18 at 4:19











  • Can you show your complete code based on my code? I am so confused

    – Lawrence Agulto
    Nov 14 '18 at 4:21











  • My complete code? That code was written straight into Stackoverflow based upon your code

    – SushiHangover
    Nov 14 '18 at 4:22











  • I mean can you modify this var conn = new SQLiteConnection(dbPath, true, null); and use this var db = DependencyService.Get<ISQLiteDB>(); var conn = db.GetConnection();

    – Lawrence Agulto
    Nov 14 '18 at 4:25
















1















  1. Use the non-async Insert in one background thread, instead of 3000 separate async calls...


  2. Re-use the List from your DeserializeObject step instead of creating new local objects that will just be thrown away on each loop iteration.


  3. No need to assign all those json properties (item.XXX) to another local variable, just update the properties of each existing ContactsData as needed before inserting it into the DB.



Example using SQLiteConnection:



// 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();
});


Example using SQLiteAsyncConnection:



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...





share|improve this answer


























  • I am using my code to sync data from my server into my sqlite database can I still use var db = DependencyService.Get<ISQLiteDB>(); var conn = db.GetConnection();

    – Lawrence Agulto
    Nov 14 '18 at 4:18











  • DependencyService? yes, just add a another Get that returns the non-async connection....

    – SushiHangover
    Nov 14 '18 at 4:19











  • Can you show your complete code based on my code? I am so confused

    – Lawrence Agulto
    Nov 14 '18 at 4:21











  • My complete code? That code was written straight into Stackoverflow based upon your code

    – SushiHangover
    Nov 14 '18 at 4:22











  • I mean can you modify this var conn = new SQLiteConnection(dbPath, true, null); and use this var db = DependencyService.Get<ISQLiteDB>(); var conn = db.GetConnection();

    – Lawrence Agulto
    Nov 14 '18 at 4:25














1












1








1








  1. Use the non-async Insert in one background thread, instead of 3000 separate async calls...


  2. Re-use the List from your DeserializeObject step instead of creating new local objects that will just be thrown away on each loop iteration.


  3. No need to assign all those json properties (item.XXX) to another local variable, just update the properties of each existing ContactsData as needed before inserting it into the DB.



Example using SQLiteConnection:



// 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();
});


Example using SQLiteAsyncConnection:



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...





share|improve this answer
















  1. Use the non-async Insert in one background thread, instead of 3000 separate async calls...


  2. Re-use the List from your DeserializeObject step instead of creating new local objects that will just be thrown away on each loop iteration.


  3. No need to assign all those json properties (item.XXX) to another local variable, just update the properties of each existing ContactsData as needed before inserting it into the DB.



Example using SQLiteConnection:



// 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();
});


Example using SQLiteAsyncConnection:



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...






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 14 '18 at 4:40

























answered Nov 14 '18 at 4:15









SushiHangoverSushiHangover

51k53988




51k53988













  • I am using my code to sync data from my server into my sqlite database can I still use var db = DependencyService.Get<ISQLiteDB>(); var conn = db.GetConnection();

    – Lawrence Agulto
    Nov 14 '18 at 4:18











  • DependencyService? yes, just add a another Get that returns the non-async connection....

    – SushiHangover
    Nov 14 '18 at 4:19











  • Can you show your complete code based on my code? I am so confused

    – Lawrence Agulto
    Nov 14 '18 at 4:21











  • My complete code? That code was written straight into Stackoverflow based upon your code

    – SushiHangover
    Nov 14 '18 at 4:22











  • I mean can you modify this var conn = new SQLiteConnection(dbPath, true, null); and use this var db = DependencyService.Get<ISQLiteDB>(); var conn = db.GetConnection();

    – Lawrence Agulto
    Nov 14 '18 at 4:25



















  • I am using my code to sync data from my server into my sqlite database can I still use var db = DependencyService.Get<ISQLiteDB>(); var conn = db.GetConnection();

    – Lawrence Agulto
    Nov 14 '18 at 4:18











  • DependencyService? yes, just add a another Get that returns the non-async connection....

    – SushiHangover
    Nov 14 '18 at 4:19











  • Can you show your complete code based on my code? I am so confused

    – Lawrence Agulto
    Nov 14 '18 at 4:21











  • My complete code? That code was written straight into Stackoverflow based upon your code

    – SushiHangover
    Nov 14 '18 at 4:22











  • I mean can you modify this var conn = new SQLiteConnection(dbPath, true, null); and use this var db = DependencyService.Get<ISQLiteDB>(); var conn = db.GetConnection();

    – Lawrence Agulto
    Nov 14 '18 at 4:25

















I am using my code to sync data from my server into my sqlite database can I still use var db = DependencyService.Get<ISQLiteDB>(); var conn = db.GetConnection();

– Lawrence Agulto
Nov 14 '18 at 4:18





I am using my code to sync data from my server into my sqlite database can I still use var db = DependencyService.Get<ISQLiteDB>(); var conn = db.GetConnection();

– Lawrence Agulto
Nov 14 '18 at 4:18













DependencyService? yes, just add a another Get that returns the non-async connection....

– SushiHangover
Nov 14 '18 at 4:19





DependencyService? yes, just add a another Get that returns the non-async connection....

– SushiHangover
Nov 14 '18 at 4:19













Can you show your complete code based on my code? I am so confused

– Lawrence Agulto
Nov 14 '18 at 4:21





Can you show your complete code based on my code? I am so confused

– Lawrence Agulto
Nov 14 '18 at 4:21













My complete code? That code was written straight into Stackoverflow based upon your code

– SushiHangover
Nov 14 '18 at 4:22





My complete code? That code was written straight into Stackoverflow based upon your code

– SushiHangover
Nov 14 '18 at 4:22













I mean can you modify this var conn = new SQLiteConnection(dbPath, true, null); and use this var db = DependencyService.Get<ISQLiteDB>(); var conn = db.GetConnection();

– Lawrence Agulto
Nov 14 '18 at 4:25





I mean can you modify this var conn = new SQLiteConnection(dbPath, true, null); and use this var db = DependencyService.Get<ISQLiteDB>(); var conn = db.GetConnection();

– Lawrence Agulto
Nov 14 '18 at 4:25


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53292827%2finsert-data-from-server-to-sqlite-database%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







這個網誌中的熱門文章

Tangent Lines Diagram Along Smooth Curve

Yusuf al-Mu'taman ibn Hud

Zucchini