在我的Windows Strore应用程序中,我在隔离存储中有SQLite数据库
我使用sqlite-net库。
要将数据保存到DataBase,请使用以下命令:
public static async Task Save<T>(List<T> items)
{
var serverFolder = await ApplicationData.Current.LocalFolder.GetFolderAsync("FolgerName");
var storageFile = await serverFolder.GetFileAsync("DataBaseName.sqlite");
using (var db = new SQLiteConnection(storageFile.Path))
{
Debug.WriteLine("Save to DataBase " + (typeof(T)) + " started " + DateTime.Now.Minute + ":" + DateTime.Now.Second + ":" + DateTime.Now.Millisecond);
try
{
foreach (var item in items)
{
db.InsertOrReplace(item);
}
Debug.WriteLine("Save to DataBase " + (typeof(T)) + " success " + DateTime.Now.Minute + ":" + DateTime.Now.Second + ":" + DateTime.Now.Millisecond);
}
catch
(SQLiteException ex)
{
Debug.WriteLine("Save to DataBase " + (typeof(T)) + " error. Result: " + ex.Result + " Message: " + ex.Message);
}
}
}
我对表现有疑问:
每个包含60个字段的1226个对象在4个半MINUTES中保存在DataBase中!
这很正常吗?
我怎样才能让它更快?
更新
当我使用时:
public static async Task Save<T>(List<T> items, Server server) where T : IHasId
{
var serverFolder = await ApplicationData.Current.LocalFolder.GetFolderAsync(server.FolgerName);
var storageFile = await serverFolder.GetFileAsync("kaliti.sqlite");
using (var db = new SQLiteConnection(storageFile.Path))
{
Debug.WriteLine("Save to DataBase " + (typeof(T)) + " started" + String.Format("{0:d/M/yyyy HH:mm:ss}", DateTime.Now));
try
{
var table = db.Table<T>();
var idList = new List<int>();
foreach (var i in table)
{
idList.Add(i.Id);
}
foreach (var item in items)
{
if (idList.Contains(item.Id))
{
db.Delete<T>(item.Id);
}
db.Insert(item);
}
Debug.WriteLine("Save to DataBase " + (typeof(T)) + " success" + String.Format("{0:d/M/yyyy HH:mm:ss}", DateTime.Now));
}
catch
(SQLiteException ex)
{
Debug.WriteLine("Save to DataBase " + (typeof(T)) + " error. Result: " + ex.Result + " Message: " + ex.Message);
}
}
}
和DataBase为空我有相同的东西。
答案 0 :(得分:1)
您需要在事务内运行尽可能多的数据库调用。这样做可以大大加快速度。这是一个示例事务,使用第一个示例中的代码:
...
try
{
db.RunInTransaction(() =>
{
foreach (var item in items)
{
db.InsertOrReplace(item);
}
});
...