批次更新資料

來源:互聯網
上載者:User
資料 最近做一項目,遇到了批次更新資料,代碼 如下:

一個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>





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.