您好,登錄后才能下訂單哦!
如何在Asp.Net中使用Bulk實(shí)現(xiàn)一個(gè)數(shù)據(jù)插入功能?很多新手對此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。
主要功能代碼如下:
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++)//循環(huán)往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";//數(shù)據(jù)庫表名 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)) });//數(shù)據(jù)庫表結(jié)構(gòu) return dt; } public bool IsReusable { get { return false; } } } }
看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進(jìn)一步的了解或閱讀更多相關(guān)文章,請關(guān)注億速云行業(yè)資訊頻道,感謝您對億速云的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。