本文实例讲述了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;
      }
    }
  }
}

希望本文所述对大家的asp.net程序设计有所帮助。

标签:
Asp.Net,Bulk,批量,插入,数据

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
狼山资源网 Copyright www.pvsay.com

评论“Asp.Net使用Bulk实现批量插入数据”

暂无“Asp.Net使用Bulk实现批量插入数据”评论...