Asp.Net使用Bulk实现批量插入数据
本文实例讲述了Asp.Net使用Bulk实现批量插入数据的方法,分享给大家供大家参考之用。具体方法如下:
主要功能代码如下:
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Web; usingSystem.Diagnostics; usingSystem.Data; usingSystem.Data.SqlClient; usingSystem.Configuration; usingFx678Member.Framework.Exceptions; namespaceMeiYuanJinYe.Admin.HttpHandler { ///<summary> ///CreateAccount的摘要说明 ///</summary> publicclassCreateAccount:IHttpHandler { publicvoidProcessRequest(HttpContextcontext) { context.Response.ContentType="text/plain"; GuidclassRoomId=Guid.Parse(context.Request["ClassRoomId"]); intCount=int.Parse(context.Request["Count"]); DataTabledt=GetTableSchema(); Randomran=newRandom(); for(inti=0;i<Count;i++)//循环往DataTable中赋值 { DataRowr=dt.NewRow(); r[1]=ran.Next(10000000,100000000); r[2]=ran.Next(10000000,100000000); r[3]=classRoomId; r[4]=DateTime.Now; r[5]=1; dt.Rows.Add(r); } BulkToDB(dt); context.Response.Write(BulkToDB(dt)?"ok":"error"); context.Session["dataTable"]=dt; } publicvoidBulkToDB(DataTabledt) { SqlConnectionsqlConn=newSqlConnection(ConfigurationManager.AppSettings["ConnString"]); SqlBulkCopybulkCopy=newSqlBulkCopy(sqlConn); bulkCopy.DestinationTableName="ClassRoomAccount";//数据库表名 bulkCopy.BatchSize=dt.Rows.Count; try { sqlConn.Open(); if(dt!=null&&dt.Rows.Count!=0) bulkCopy.WriteToServer(dt); } catch(Exceptionex) { newAppException("批量生成直播室账号异常",ex); } finally { sqlConn.Close(); if(bulkCopy!=null) bulkCopy.Close(); } } publicDataTableGetTableSchema() { DataTabledt=newDataTable(); dt.Columns.AddRange(newDataColumn[]{ newDataColumn("AccountId",typeof(int)), newDataColumn("AccountName",typeof(string)), newDataColumn("Password",typeof(string)), newDataColumn("ClassRoomId",typeof(Guid)), newDataColumn("AddDate",typeof(DateTime)), newDataColumn("IsActive",typeof(int)) });//数据库表结构 returndt; } publicboolIsReusable { get { returnfalse; } } } }
希望本文所述对大家的asp.net程序设计有所帮助。