SQLite數據庫作為一般單機版軟件的數據庫,是非常優秀的,我目前單機版的軟件產品線基本上全部替換Access作為優選的數據庫了,在開發過程中,有時候需要批量寫入數據的情況,發現傳統的插入數據模式非常慢,幾千條數據的寫入或者更新可能需要好幾分鍾時間,而SqlServer則相同的操作可能幾秒即可,有無更好的方法來提高它的響應速度呢?答案是有的,就是采用事務提交,默認SQLite的數據庫插入操作,如果沒有采用事務的話,它每次寫入提交,就會觸發一次事務操作,而這樣幾千條的數據,就會觸發幾千個事務的操作,這就是時間耗費的根源。本文通過詳細代碼介紹如何使用事務來提高整個批量插入數據的速度,並以實際的Winform開發框架中的字典管理模塊的批量插入功能來進行介紹,通過前后速度的對比,使得事務操作提高響應速度更有說服力。
由於一些項目需要,字典管理模塊需要批量錄入數據,因此改善了我的《Winform開發框架》中的字典管理模塊,在字典管理模塊增加一個批量添加的功能,如下所示。
對一些診斷的數據錄入,一般情況下都可能是幾千條的數據,還有可能更多的一些分類字典,那么如果每次都需要等待幾分鍾或者幾十分鍾,那么這樣的響應體驗肯定很差。
為了提高響應速度,我這里使用了事務操作,整個事務操作是基於EnterpriseLibray類庫的數據庫操作,由於我已經在框架的基類中做了封裝,因此我們這里看到整個處理過程即可。
其中MyRegion里面的代碼就是遍歷每行的數據,構造數據字典對象和排序號,然后調用InsertDictData函數進行數據的錄入。其中InsertDictData函數的代碼是
/// <summary> /// 使用事務參數,插入數據,最后統一提交事務處理 /// </summary> /// <param name="dictData">字典數據</param> /// <param name="seq">排序</param> /// <param name="trans">事務對象</param> private void InsertDictData(string dictData, string seq, DbTransaction trans) { if (!string.IsNullOrWhiteSpace(dictData)) { DictDataInfo info = new DictDataInfo(); info.Editor = LoginID; info.LastUpdated = DateTime.Now; info.DictType_ID = this.txtDictType.Tag.ToString(); info.Name = dictData.Trim(); info.Value = dictData.Trim(); info.Remark = this.txtNote.Text.Trim(); info.Seq = seq; bool succeed = BLLFactory<DictData>.Instance.Insert(info, trans); } }
整個插入功能按鈕的處理全部代碼如下所示。
private void btnOK_Click(object sender, EventArgs e) { string[] arrayItems = this.txtDictData.Lines; int intSeq = -1; int seqLength = 3; string strSeq = this.txtSeq.Text.Trim(); if (int.TryParse(strSeq, out intSeq)) { seqLength = strSeq.Length; } if (arrayItems != null && arrayItems.Length > 0) { DbTransaction trans = BLLFactory<DictData>.Instance.CreateTransaction(); if (trans != null) { try { #region MyRegion foreach (string strItem in arrayItems) { if (this.radSplit.Checked) { if (!string.IsNullOrWhiteSpace(strItem)) { string[] dataItems = strItem.Split(new char[] { ',', ',', ';', ';', '/', '、' }); foreach (string dictData in dataItems) { #region 保存數據 string seq = ""; if (intSeq > 0) { seq = (intSeq++).ToString().PadLeft(seqLength, '0'); } else { seq = string.Format("{0}{1}", strSeq, intSeq++); } InsertDictData(dictData, seq, trans); #endregion } } } else { #region 保存數據 if (!string.IsNullOrWhiteSpace(strItem)) { string seq = ""; if (intSeq > 0) { seq = (intSeq++).ToString().PadLeft(seqLength, '0'); } else { seq = string.Format("{0}{1}", strSeq, intSeq++); } InsertDictData(strItem, seq, trans); } #endregion } } #endregion trans.Commit(); ProcessDataSaved(this.btnOK, new EventArgs()); MessageDxUtil.ShowTips("保存成功"); this.DialogResult = DialogResult.OK; } catch (Exception ex) { trans.Rollback(); LogTextHelper.Error(ex); MessageDxUtil.ShowError(ex.Message); } } } }
上面的批量插入,經過前后的測試,2千條數據批量插入SQLite數據庫,需要大概3~4分鍾左右,如果采用了事務操作,則在1~2秒內寫入完成,速度提高不知道多少倍。如果是操作數據比較多的,強烈建議使用事務進行操作,可以給客戶很好的體驗效果。
如果嫌上面的代碼復雜,可以看下面的講解代碼可能就明白了
using (DbTransaction dbTrans = conn.BeginTransaction()) { using (DbCommand cmd = conn.CreateCommand()) { cmd.CommandText = "INSERT INTO MyTable(MyValue) VALUES(?)"; DbParameter Field1 = cmd.CreateParameter(); cmd.Parameters.Add(Field1); for (int n = 0; n < 100000; n++) { Field1.Value = n + 100000; cmd.ExecuteNonQuery(); } } }
上面是一種比較簡單原始的事務操作,如果批量插入數據,同樣能夠起到一樣的效果。