批量更新数据

最近做一项目,遇到了批量更新数据,代码 如下:

一个update的例子:
<%@ Page language="C#" Debug="true" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<script runat="server">
void Page_Load(object sender, System.EventArgs e){
     SqlConnection conn = new SqlConnection("server=localhost;uid=sa;pwd=kingapex;database=tourmsg");
     SqlDataAdapter da = new SqlDataAdapter();
     SqlCommand cmd = new SqlCommand("select top 2 id,groupnumber as groupnumber1 from [grouptb]",conn);
     DataSet ds = new DataSet();
     conn.Open();
     da.SelectCommand = cmd;
     da.Fill(ds,"grouptb");


     for(int i=0;i<ds.Tables["grouptb"].Rows.Count;i++)
     {

           Response.Write(ds.Tables["grouptb"].Rows[1]+"<br>");
     }


     for(int i=0;i<ds.Tables["grouptb"].Rows.Count;i++)
     {
           ds.Tables["grouptb"].Rows.BeginEdit();
           ds.Tables["grouptb"].Rows[1] = "wangfengrr";
           ds.Tables["grouptb"].Rows.EndEdit();
     }

        String updateCmd = "Update grouptb set groupnumber = @groupnumber Where Id=@id";


     cmd = new SqlCommand(updateCmd, conn);
     cmd.Parameters.Add("@id",SqlDbType.Int,4,"id");
     cmd.Parameters.Add("@groupnumber",SqlDbType.Char,10,"groupnumber1");

     da.UpdateCommand = cmd;
     da.Update(ds,"grouptb");
     ds.AcceptChanges();

     conn.Close();
    

}
</script>

下面是一个insert 的例子:

<%@ Page language="C#" Debug="true" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<script runat="server">
void Page_Load(object sender, System.EventArgs e){

        //建立DataTable数据源
        DataTable Dt = new DataTable();

        DataRow Dr;

 Dt.Columns.Add(new DataColumn("groupnumber"));

 

 for(int j =0;j<3;j++){

  Dr=Dt.NewRow();

  Dr[0]="groupnumber"+j.ToString();

  Dt.Rows.Add(Dr);

 }


SqlConnection conn = new SqlConnection("server=localhost;uid=sa;pwd=kingapex;database=tourmsg");


SqlDataAdapter MyAdapter = new SqlDataAdapter();

//建立InsertCommand
StringBuilder sb = new StringBuilder("");
sb.Append("INSERT grouptb (groupnumber) VALUES(");
sb.Append("@groupnumber)");
MyAdapter.InsertCommand = new SqlCommand();
MyAdapter.InsertCommand.CommandText = sb.ToString();
MyAdapter.InsertCommand.Connection = conn;


SqlParameter p1 = new SqlParameter("@groupnumber", SqlDbType.VarChar, 40);
p1.SourceVersion = DataRowVersion.Current;
p1.SourceColumn = "groupnumber"; // or p1.SourceColumn = Dt.Columns[0].ColumnName;
MyAdapter.InsertCommand.Parameters.Add(p1);

//Update
MyAdapter.Update(Dt);

 conn.Close();
}
</script>

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页