2013-02-27 94 views
2

我正在使用ASP.NET Web窗体并试图从SQL服务器加载数据。下面是我如何做到这一点的伪代码:减少往返数据库

connect1 = connect("database") 
categories = connect.query("select * from category") 
loop categories as category 

    print category   

    connect2 = connect("database") 
    subCategories = connect2.query("select * from subCategory where category = @0", category) 
    loop subCategories as subCategory 

      print subCategory    

      connect3 = connect("database") 
      items = connect3.query("select * from item where subCategory = @0", subCategory) 
      loop items as item 
       print item 
      end loop 'items 
      connect3.close 

    end loop 'subcategories 
    connect2.close 

end loop 'categories 
connect1.close 

正如你所看到的,有很多往返于我的脚本发生的情况,这是好的,当我只有几个记录,但有数百打交道时或更多,这需要永远显示数据。

我该怎么做才能减少往返次数?我想从数据库中一次获得所有数据,然后在应用程序端对它们进行分类,但这有可能吗?

+0

在一个查询中完成所有操作。看看[CTE](http://msdn.microsoft.com/en-us/library/ms190766%28v=sql.105%29.aspx)。这个问题更适合[codereview](http://codereview.stackexchange.com/) – nunespascal 2013-02-27 08:43:39

+0

@nunespascal为什么选择CTE? – dpp 2013-02-27 08:48:49

+0

CTE,以便您可以递归地获取子类别。 – nunespascal 2013-02-27 09:08:26

回答

2

为什么不通过一个含有连接的查询获取所需的所有数据,然后在客户端进行筛选;或者你可以做的其他方式(它没有太多的数据)将数据作为XML获取,将其反序列化为可循环迭代。

,我看到它,你做

categories = connect.query("select * from category"); 

因此,所有你需要的是:手动映射

whole_data = connect.query("select * from category c inner join subCategory sc on c.id = sc.id inner join item i on i.id = si.id") /*or some kind of*/ 
/*let me think that whole_data is a list of objects, not a dataset*/ 
categories = whole_data.Distinct(d => d.category); 
subCategories = whole_data.Distinct(d => d.subCategories); 
/*and then do your loops*/ 

C#代码可能是这样的:

 using (var connection = new SqlConnection(connString)) 
     { 
      connection.Open(); 
      var command = connection.CreateCommand(); 
      command.CommandText = "select * from ..."; 

      var reader = command.ExecuteReader(); 
      while (reader.Read()) 
      { 
       var a = reader.GetInt32(0); 
       var b = reader.GetString(1); 
       /*so basically you read all fields that you get from DB and build object here, then you add it to List or any other kind of collection*/ 
      } 
     } 
+0

这就是我的想法,但问题是,如何?有这样的事情,我需要在应用程序端查询结果集的库或类。 – dpp 2013-02-27 08:51:19

+0

伪代码我会怎么做:) – Sergio 2013-02-27 08:58:40

+0

我明白,你正在尝试帮助,但我不寻找伪代码或实际代码,如果你知道任何图书馆或类,我可以用来查询“whole_data”,它会是什么? – dpp 2013-02-27 09:01:36

1

取决于延迟到数据库,即使汇集,连接也可能需要很长时间。为了避免这种情况,请将所有连接设置在循环之外。也就是说,不要嵌套连接。相反,它的结构是这样的:

Connect1 = connect("database") 
Connect2 = connect("database") 
Connect3 = connect("database") 

sql 1 nest 
    sql 2 nest 
     sql 3 nest 
     end nest 
    end nest 
end nest 

close connections. 

如果每个循环10个条目,并连接需要10毫秒,你会花10×10×10 = 1000个毫秒只是在做连接。把它们放在巢外,然后你只花30 mS连接。在每个嵌套完成时关闭数据读取器,以便可以重新使用连接。

当然,对于您展示的示例,执行单个查询是最佳解决方案。 但是,如果您的查询是有选择的,并且您需要执行一些无法在查询中进行组合的业务逻辑,那么请始终将您的连接移到循环之外。