C#sqlite事务循环高效插入数据,天下文章一大抄,本例亲自测试过,速度嘎嘎的。

                        string n = string.Empty;
                       
string i = string.Empty;
                       
string d = string.Empty;
                        DateTime cd;

SQLiteConnection conn = new SQLiteConnection(SQLiteHelper.ConnectionString); SQLiteCommand commd = new SQLiteCommand(conn); conn.Open(); SQLiteTransaction tran = conn.BeginTransaction(); commd.Transaction = tran; commd.Parameters.Clear(); commd.CommandType = CommandType.Text; try { wt = new Stopwatch(); wt.Reset(); wt.Start(); cmdtext = "REPLACE INTO XXX (name,i,CBdate,crdate) values(@db,@i,@cbdate,@crdate)"; commd.CommandText = cmdtext; for (int i = 0; i < t; i++) { n = Convert.ToString(gv.GetRowCellValue(i, "name")); i = Convert.ToString(gv.GetRowCellValue(i, "i")); d = Convert.ToString(gv.GetRowCellValue(i, "cbdate")); cd = Convert.ToDateTime(gv.GetRowCellValue(i, "crdate")); SQLiteParameter[] p = new SQLiteParameter[] { new SQLiteParameter("@db", n), new SQLiteParameter("@i", ip), new SQLiteParameter("@cbdate",d), new SQLiteParameter("@crdate",cd)}; if (p != null && p.Length > 0) { commd.Parameters.AddRange(p); } commd.ExecuteNonQuery(); } } tran.Commit(); } catch (Exception err) { tran.Rollback(); ComMsg.MsgErr(err.Message); throw new Exception(err.Message); } finally { conn.Close(); ComMsg.MsgOk(string.Format("操作结束,耗时{0}毫秒", wt.ElapsedMilliseconds)); }

//速度相当不错,三几千条数据毫秒级别,相比直接插入速度不知道快多少。

 本例有待进一步封装,以便通用。

posted @ 2013-07-27 22:13  永远的菜鸟@me  阅读(840)  评论(0编辑  收藏  举报