最近做一项目,遇到了批量更新数据,代码 如下:
一个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>