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();
       }


  • 相关阅读:
    【NOI2015】品酒大会 SAM
    4566: [Haoi2016]找相同字符 SAM
    3709: [PA2014]Bohater 贪心
    1925: [Sdoi2010]地精部落 dp, 抖动子序列
    4205: 卡牌配对 最大流+建图技巧
    留言板
    self-introduction
    最近比赛
    STOI补番队胡策
    BZOJ 3503: [Cqoi2014]和谐矩阵( 高斯消元 )
  • 原文地址:https://www.cnblogs.com/pains/p/890173.html
Copyright © 2011-2022 走看看