Sqlite 快速插入数据到本地表中

用原始Insert方法太慢,网上找到了
https://www.cnblogs.com/yisen-code/p/6897524.html

思路是:

开启事务,开启预处理,然后把SQL用参数传入具体值来快速写入数据,本地测试,2W条写入本地不到1秒。

分享给大家

        public void Quick_HG_Insert(DataTable dt)
        {

            try
            {
                var conn = GetConnection();
                using (var dbTrans = conn.BeginTransaction())
                {
                    var cmd = new SQLiteCommand();
                    cmd.Connection = conn;
                    cmd.Prepare();//开启预处理

                    cmd.CommandText = "Insert Into BoxScanRank(BoxScanNO,BoxCount,PONO,Rank) Values(@BoxScanNO,@BoxCount,@PONO,@Rank)";
                    var sp = new SQLiteParameter[4];
                    foreach (DataRow row in dt.Rows)
                    {
                        sp[0] = new SQLiteParameter("@BoxScanNO", row["BoxScanNO"]);
                        sp[1] = new SQLiteParameter("@BoxCount", row["BoxCount"]);
                        sp[2] = new SQLiteParameter("@PONO", row["PONO"]);
                        sp[3] = new SQLiteParameter("@Rank", row["Rank"]);
                        cmd.Parameters.AddRange(sp);
                        cmd.ExecuteNonQuery();
                    }
                    dbTrans.Commit();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

 

posted @ 2018-06-11 21:29  Aleax  阅读(585)  评论(0编辑  收藏  举报