C# 4.0 For循环与sqlcommand一起使用
我有一个存储过程,它返回两次之间所有列的平均值,即04:00到04:14。我希望有一个选项,以相同的间隔返回24小时的结果(在本例中,间隔为15分钟。04:14-04:00),因此结果如下所示:C# 4.0 For循环与sqlcommand一起使用,c#-4.0,ado.net,sqlcommand,C# 4.0,Ado.net,Sqlcommand,我有一个存储过程,它返回两次之间所有列的平均值,即04:00到04:14。我希望有一个选项,以相同的间隔返回24小时的结果(在本例中,间隔为15分钟。04:14-04:00),因此结果如下所示: using(SqlCommand cmd = new SqlCommand()) { //Setup the command object and connection. for(int i=0; i<....) { cmd.CommandText = "set your dy
using(SqlCommand cmd = new SqlCommand())
{
//Setup the command object and connection.
for(int i=0; i<....)
{
cmd.CommandText = "set your dynamic sql here based on current iteration";
var reader = cmd.ExecuteReader();
//Now read you rows
}
}
00:00-00:14=x.xxx
00:15-00:29=x.xxx
我假设我不能在using语句中更改sqlcommand(特别是存储过程的参数),并且需要将for循环放在前面,从而每次都创建一个新的sqlcommand对象
for(int i = x; .....)
{
using (SqlCommand cmd = new SqlCommand())
{
}
}
谢谢这是一种很好的方法,只要您不每次打开新连接。但是,我不确定性能影响。如果您真的想使用for循环,那么您应该执行以下操作:
using(SqlCommand cmd = new SqlCommand())
{
//Setup the command object and connection.
for(int i=0; i<....)
{
cmd.CommandText = "set your dynamic sql here based on current iteration";
var reader = cmd.ExecuteReader();
//Now read you rows
}
}
使用(SqlCommand cmd=new SqlCommand())
{
//设置命令对象和连接。
for(int i=0;Ithank for correction。出于某种原因,我一直认为SqlCommand上的disposer会关闭连接。SqlConnection.Dispose
方法会关闭连接,因此您部分是对的。