如题。
打个比方:页面上用 CheckBoxList 绑定了当前所有的用户,我勾选中了其中的1000个用户,然后按下删除按钮,大家通常都是怎样去删除掉这1000个用户的呢?请阐明你的思路,最好列出简单的代码,我使用的是 .net2.0 + Sql Server2000 ,谢谢。
打个比方:页面上用 CheckBoxList 绑定了当前所有的用户,我勾选中了其中的1000个用户,然后按下删除按钮,大家通常都是怎样去删除掉这1000个用户的呢?请阐明你的思路,最好列出简单的代码,我使用的是 .net2.0 + Sql Server2000 ,谢谢。
string whereClause = string.Empty; foreach (遍历CheckBoxList)
{ if (选中)
{
if (whereClause == string.Empty)
whereClause += "'" + 取值 + "'";
else
whereClause += ",'" + 取值 + "'";
}
}
if (whereClause != string.Empty)
{
SqlConnection cn = new SqlConnection(...);
string strSQL = "delete from mytable where id in (" + whereClause + ")";
SqlCommand cmd = new SqlCommand(strSQL, cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
I admire you ... hahaha
服务器的作业频繁度~。
比如有一个excel档,里面有几千条甚至几万条记录,要insert到
DB中,如何作业?如果是循环插入,是否会由于频繁操作server
导致一些问题~~~
this is better way.
括号里面根据选中结点直接拼接,不过别忘了用StringBuilder
最好用构造存储过程。
foreach (ListItem item in CheckBoxList1.Items)
{
if (item.Selected == true)
{
s = item.Value;
string[] slist = s.Split(',');
foreach (string id in slist)
{
//根据id删除
}
}
}
一般情况下显示数据表gridview用的多一些,在gridview每行的第一个单元格添加一个checkbox,在button事件中
protected void Button2_Click(object sender, EventArgs e)
{
sqlcon = new SqlConnection(strCon);
SqlCommand sqlcom;
for (int i = 0; i <= GridView1.Rows.Count - 1; i++)
{
CheckBox cbox = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
if (cbox.Checked == true)
{ string sqlstr = "delete from 表 where 号码='" + GridView1.DataKeys[i].Value + "'";
sqlcom = new SqlCommand(sqlstr, sqlcon);
sqlcon.Open();
sqlcom.ExecuteNonQuery();
sqlcon.Close();
}
}
bind();
}
bind函数用来绑定数据
public void bind()
{
string sqlstr = "select top 5 * from 表";
sqlcon = new SqlConnection(strCon);
SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
DataSet myds = new DataSet();
sqlcon.Open();
myda.Fill(myds, "tb_Member");
GridView1.DataSource = myds;
GridView1.DataKeyNames = new string[] ...{ "号码" };
GridView1.DataBind();
sqlcon.Close();
}
循环删除的人,根本就没有做过任何的效率测验,放大一下,到1w条,这样的做法会导致远程的i/o非常剧烈
拼接字符串是个效率不错的办法,前提是安全性和数据完整性要求不高的情况下。。另,如果只是做单表删除,可以启动数据库的事务,再循环体里面做删除,循环结束后一起提交。 效率也不会差。也可以支持参数化的删除,安全性也能得到提高。原因:启动事务之后,一直保持连接,所以对数据库的访问相当于建立一次连接,提交,关闭连接。
循环删除如果用存储过程,删除1w条来说应该不会导致远程的i/o很剧烈吧.
应该会比拼接字符串快很多.
瞎想的,可用?
1:先遍历CheckBoxList,获取所有选中的id,作为一个数组传到存储过程里,存储过程循环该数组做删除,2次循环
2:遍历CheckBoxList,每获取一个选中的做一次删除,1次循环
更长,像这样删除,其实做事务形式的参数化删除也是蛮快的,我这里试了一下按主键删除的话,基本上也是
瞬间完成了。
begin tran
comm.commtext=...
for(...)
comm.para=value;
comm.exec
end tran
构造where ID in "...,..,..."的方式没试过.
如果数据据量比较大,构造where子句的方式应该快些.