C#:这是为 DAAB 使用 SqlDataReader 的正确方法吗 [英] C#: Is this the correct way to use the SqlDataReader for DAAB

查看:26
本文介绍了C#:这是为 DAAB 使用 SqlDataReader 的正确方法吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

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

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);
    }
}

这篇关于C#:这是为 DAAB 使用 SqlDataReader 的正确方法吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆