for循环后从DB中检索数据到数据集 [英] Retrieving Data to dataset from DB after for loop
本文介绍了for循环后从DB中检索数据到数据集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,
我需要在循环中传递id的查询(即for(int i = 0; i< 45; i ++)
每次迭代后
我需要在dataSet中检索数据。这样我就可以在循环后查看所有数据。
ex:
Hi everyone,
I've a query to which i need to pass the id in loop,(i.e., for(int i=0;i<45;i++)
after every iteration i need that retrieved data in dataSet. so that i can view that all data after the loop.
ex:
for (int i = 0; i < 45; i++)
{
string str = " SELECT * from Table1 where id='"+i+"'";
SqlCommandcmd = new SqlCommand(str, conn);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adp.Fill(dt);
gridview1.DataSource = dt;
gridview1.DataBind();
}
推荐答案
这样做一次只能获得一个ID。
如果您使用的是SQL Server,则可以使用表值参数。
使用获取
循环用ID填充DataTable,然后将它们作为参数传递给查询。
SQL Server 2008用户定义的表类型和表值参数 [ ^ ]
Doing it that way will get you only one ID at a time.
If you are using SQL Server, you can use a Table-Valued Parameter.
Use yourfor
loop to fill a DataTable with the IDs, then pass them as a parameter to the query.
SQL Server 2008 User Defined Table Types and Table-Valued Parameters[^]
您可以通过单次调用数据库来实现此目的。查看下面的代码块。我做了两个小改动,这样可以用更少的时间给出正确的结果。
You can achieve this with single call of database. Review below block of code. I make two small change and this will give proper result with less time.
string strIds = string.Empty;
for (int i = 0; i < 45; i++)
{
strIds = strIds == string.Empty ? "'" + i.ToString() + "'" : (",'" + i.ToString() + "'");
}
string str = " SELECT * from Table1 where id IN (" + strIds + ")";
SqlCommandcmd = new SqlCommand(str, conn);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adp.Fill(dt);
gridview1.DataSource = dt;
gridview1.DataBind();
这篇关于for循环后从DB中检索数据到数据集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文