如何在Asp.Net中使用Bulk实现一个数据插入功能?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
主要功能代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Diagnostics; using System.Data; using System.Data.SqlClient; using System.Configuration; using Fx678Member.Framework.Exceptions; namespace MeiYuanJinYe.Admin.HttpHandler { /// <summary> /// CreateAccount 的摘要说明 /// </summary> public class CreateAccount : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; Guid classRoomId = Guid.Parse(context.Request["ClassRoomId"]); int Count = int.Parse(context.Request["Count"]); DataTable dt = GetTableSchema(); Random ran = new Random(); for (int i = 0; i < Count; i++)//循环往DataTable中赋值 { DataRow r = 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; } public void BulkToDB(DataTable dt) { SqlConnection sqlConn = new SqlConnection(ConfigurationManager.AppSettings["ConnString"]); SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConn); bulkCopy.DestinationTableName = "ClassRoomAccount";//数据库表名 bulkCopy.BatchSize = dt.Rows.Count; try { sqlConn.Open(); if (dt != null && dt.Rows.Count != 0) bulkCopy.WriteToServer(dt); } catch (Exception ex) { new AppException("批量生成直播室账号异常", ex); } finally { sqlConn.Close(); if (bulkCopy != null) bulkCopy.Close(); } } public DataTable GetTableSchema() { DataTable dt = new DataTable(); dt.Columns.AddRange(new DataColumn[]{ new DataColumn("AccountId",typeof(int)), new DataColumn("AccountName",typeof(string)), new DataColumn("Password",typeof(string)), new DataColumn("ClassRoomId",typeof(Guid)), new DataColumn("AddDate",typeof(DateTime)), new DataColumn("IsActive",typeof(int)) });//数据库表结构 return dt; } public bool IsReusable { get { return false; } } } }
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。