How to bulk insert into SQLITE database?

不打扰是莪最后的温柔 提交于 2019-12-06 06:10:21

Try the InsertAll and UpdateAll functions. Hopefully this opens up the database table just once and inserts/updates everything at once. You will need to figure out which objects to insert/update ahead of time, but this should still really speed things up.

List<TickRecords> updates = new List<TickRecords>(); 

List<TickRecords> inserts = new List<TickRecords>();  

foreach ( var tickRecord in tickRecords ) 
{   
    if ( tickRecord.Id == 0 )
    {       
        updates.Add(tickRecord);
    }
    else
    {       
        inserts.Add(tickRecords);
     } 
}



using ( var db = new SQLiteConnection( new SQLitePlatformWinRT(), DbPath ) ) 
{
     db.InsertAll(inserts);
     db.UpdateAll(updates);
}
Bikswan

You should insert all 20K records in single sqllite transaction.

Something like this:

    public static void AddOrUpdateTickRecords( ObservableCollection<TickRecord> tickRecords )
        {
        // Create a new connection
        using ( var db = new SQLiteConnection( new SQLitePlatformWinRT(), DbPath ) )
            {
            db.BeginTransaction();
            try
                {
                foreach ( var tickRecord in tickRecords )
                    {
                    if ( tickRecord.Id == 0 )
                        {
                        // New
                        db.Insert( tickRecord );
                        }
                    else
                        {
                        // Update
                        db.Update( tickRecord );
                        }
                    }

                db.Commit();
                }
            catch ( Exception )
                {
                db.Rollback();
                }
            }
        }

I modified Bibek answer a bit to match it to UWP:

        public static void AddOrUpdateTickRecords( ObservableCollection<TickRecord> tickRecords )
        {
        // Create a new connection
        using ( var db = new SQLiteConnection( new SQLitePlatformWinRT(), DbPath ) )
            {
            db.BeginTransaction();
            try
                {
                foreach ( var tickRecord in tickRecords )
                    {
                    if ( tickRecord.Id == 0 )
                        {
                        // New
                        db.Insert( tickRecord );
                        }
                    else
                        {
                        // Update
                        db.Update( tickRecord );
                        }
                    }

                db.Commit();
                }
            catch ( Exception ex )
                {
                db.Rollback();
                }
            }
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!