(1)连接数据库
public static void BulkToDB(DataTable dt) { //数据库连接 SqlConnection sqlCon = new SqlConnection("data source=.;initial catalog=Blog;user id=sa;password=123456;multipleactiveresultsets=True;application name=EntityFramework"); SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlCon); //数据表的名称 bulkCopy.DestinationTableName = "actionlogs"; bulkCopy.BatchSize = dt.Rows.Count; try { sqlCon.Open(); if (dt != null && dt.Rows.Count != 0) { bulkCopy.WriteToServer(dt); } } catch (Exception ex) { throw ex; } finally { sqlCon.Close(); if (bulkCopy != null) { bulkCopy.Close(); } } }
(2)获取要添加数据的表的参数
public static DataTable GetTableSchema() { DataTable dt = new DataTable(); //以下为要添加数据的表的参数设置 dt.Columns.AddRange(new DataColumn[] { new DataColumn("Guid",typeof(string)), new DataColumn("LoginName",typeof(string)), new DataColumn("Name",typeof(string)), }); return dt; }
(3)在Main方法中进行调用,执行
static void Main(string[] args) { Stopwatch sw = new Stopwatch(); for(int multiply = 0; multiply < 10; multiply++) { //获取表的参数 DataTable dt = Program.GetTableSchema(); for(int count = multiply * 100000; count < (multiply + 1) * 100000; count++) { DataRow dr = dt.NewRow(); dr[0] = Guid.NewGuid().ToString(); dr[1] = "123456"; dr[2] = "郑**"; dt.Rows.Add(dr); } sw.Start(); Program.BulkToDB(dt); sw.Stop(); Console.WriteLine(string.Format("Elapsed Time is {0} Milliseconds", sw.ElapsedMilliseconds)); } Console.ReadLine(); }
平时积累,用于复习,如有问题,请留言,谢谢