C#:这是使用 SqlDataReader 进行 DAAB 的正确方法吗

发布于 2024-08-27 16:59:41 字数 428 浏览 4 评论 0原文

我刚刚开始使用微软的数据访问应用程序块。关于如何正确使用该库的说明很少。只是想知道这是否是使用数据读取器的正确方法。

SqlDataReader reader = SqlHelper.ExecuteReader(config.ConnectionString, CommandType.Text, "select * from category");
List<string> a = new List<string>();
using (reader)
{
     while (reader.Read())
     {
          string t = reader.GetString(1);
          a.Add(t);
     }

     return a;
}

这样做一切都会关闭吗?是否存在内存泄漏的可能性?

I have just started using the Data Access Application Block from microsoft. There are very few instructions on the correct way to use the library. Just wanted to know if this is the correct way to use the data reader.

SqlDataReader reader = SqlHelper.ExecuteReader(config.ConnectionString, CommandType.Text, "select * from category");
List<string> a = new List<string>();
using (reader)
{
     while (reader.Read())
     {
          string t = reader.GetString(1);
          a.Add(t);
     }

     return a;
}

will everything get closed doing it this way? Is there any chance of memory leaks?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

七颜 2024-09-03 16:59:41

将阅读器初始化放入 using 块中,如果可以的话,我会避免使用列号,因为它们本质上会变成幻数。不幸的是,这只需要您使用列名称,但我发现列名称比列偏移量更不可能更改,并且您始终可以将列名称放在配置文件或其他文件中。另外,请确保考虑空列的可能性

using(var reader = SqlHelper.ExecuteReader(etc. etc. etc.))
{
    while(reader.read()){
    {
        //Only need to do this if you don't want your string to be null
        //and if the "columnName" column is nullable.
        var stringValue = reader.IsDBNull(reader.GetOrdinal("columnName") 
                        ? "" 
                        : reader.GetString(reader.GetOrdinal("columnName"));
        a.Add(stringValue);
    }
}

Put your reader initialization into the using block, and I would avoid using column numbers if you can, as they essentially turn into magic numbers. Unfortunately, that just requires you use the column names, but I have found that column names are less likely to change than column offsets, and you can always put your column names in a configuration file or something. Also, make sure you take into account the possibility for null columns

using(var reader = SqlHelper.ExecuteReader(etc. etc. etc.))
{
    while(reader.read()){
    {
        //Only need to do this if you don't want your string to be null
        //and if the "columnName" column is nullable.
        var stringValue = reader.IsDBNull(reader.GetOrdinal("columnName") 
                        ? "" 
                        : reader.GetString(reader.GetOrdinal("columnName"));
        a.Add(stringValue);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文