欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Asp.Net使用Bulk实现批量插入数据

程序员文章站 2024-02-21 11:59:40
本文实例讲述了asp.net使用bulk实现批量插入数据的方法,分享给大家供大家参考之用。具体方法如下: 主要功能代码如下: using system; us...

本文实例讲述了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程序设计有所帮助。