zoukankan      html  css  js  c++  java
  • ASP.NET中批量插入数据

    如果需要批量插入记录,可以使用SqlDataAdapter。示例

       string sql= "Select item1,item2,item3 from tableA";
       SqlConnection cn 
    =new SqlConnection("server=(local);uid=sa;pwd=;database=examonline");
       SqlDataAdapter da 
    =new SqlDataAdapter(sql, cn);
       DataSet ds
    =new DataSet();
       
    try
       
    {
           cn.Open();
           da.Fill(ds, 
    "dsTable1");
       }

       
    finally
       
    {
           cn.Close();
       }
     

    //向ds中追加要添加的批量数据
       CheckBox cb=new CheckBox();
       DataRow dr;
       
    for(int i=0;i<Datagrid1.Items.Count;i++)
       
    {
           cb
    =(CheckBox)Datagrid1.Items[i].FindControl("CheckBox1");
           
    if(cb.Checked==true)
           
    {
            dr
    =ds.Tables["dsTable1"].NewRow();
            dr[
    "item1"]=((Label)Datagrid1.Items[i].FindControl("Label1")).Text;
            dr[
    "item2"]=((Label)Datagrid1.Items[i].FindControl("Label2")).Text;
            dr[
    "item3"]=((Label)Datagrid1.Items[i].FindControl("Label3")).Text;
            ds.Tables[
    "dsTable1"].Rows.Add(dr);
           }

       }


    //在批量添加数据前的准备工作
       sql="insert into tableA(item1,item2,item3) VALUES (@item1,@item2,@item3)";
       da.InsertCommand
    =new SqlCommand(sql,cn); 
       SqlParameter param
    =new SqlParameter();
       param 
    = da.InsertCommand.Parameters.Add(new SqlParameter("@item1",SqlDbType.Char,50));
       param.SourceVersion 
    = DataRowVersion.Current;
       param.SourceColumn 
    = "item1";

       param 
    = da.InsertCommand.Parameters.Add(new SqlParameter("@item2",SqlDbType.Char,50));
       param.SourceVersion 
    = DataRowVersion.Current;
       param.SourceColumn 
    = "item2";

       param 
    = da.InsertCommand.Parameters.Add(new SqlParameter("@item3",SqlDbType.Char,50));
       param.SourceVersion 
    = DataRowVersion.Current;
       param.SourceColumn 
    = "item3";

    //批量添加数据
        try
       
    {
           cn.Open();
           da1.Update(ds,
    "dsTable1");
       }

       
    catch(Exception ex)
       
    {
           Label1.Text
    ="数据库错误:" +ex.Message.ToString();
       }

       
    finally
       
    {
           cn.Close();
       }


  • 相关阅读:
    设置屏幕分辨率的函数 回复 "董勇" 的问题
    Delphi 的内存操作函数(5): 复制内存
    汉字与区位码(1) 转换函数
    汉字与多字节编码的转换 回复 "不知道" 的问题
    一个可以显示多边形的 TMyShape 类 回复 "董勇" 的问题
    Delphi 的内存操作函数(6): 跨进程的内存分配
    Delphi 中的 IfThen 函数 回复 "深挖洞、广积粮" 的问题
    Byte 数组转字符串 回复 "不知道" 问题
    汉字与区位码(2) 分析
    获取各种编码的识别符
  • 原文地址:https://www.cnblogs.com/pains/p/890173.html
Copyright © 2011-2022 走看看