关闭datareader时出现NullReferenceException

ale*_*dru 2 .net c# ado.net

我刚刚学习使用ADO.NET,我似乎遇到了问题.我想要做的是从表中获取数据并将其插入DataTable.Here是我的代码:

public DataTable GetCategories()
    {
        SqlConnection connection = null;
        SqlDataReader reader = null;
        DataTable categories = new DataTable();

        try {
            connection = new SqlConnection();
            connection.ConnectionString = connectionString;
            connection.Open();

            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "GetCategories";
            reader = cmd.ExecuteReader();

            categories.Columns.Add("Id", typeof(int));
            categories.Columns.Add("CategoryName", typeof(int));

            while (reader.Read()) {
                int categoryId = (int)reader["Id"];
                string categoryName = (string)reader["CategoryName"];
                categories.Rows.Add(categoryId , categoryName);
            }

        }catch(Exception e){
            DataTable error = new DataTable();
            error.Columns.Add("Error");
            error.Rows.Add(e.Message);
            return error;
        }finally{
            connection.Close();
            reader.Close();
        }
        return categories;
    }
Run Code Online (Sandbox Code Playgroud)

这是我的SQL查询:

 CREATE PROCEDURE [dbo].[GetCategories]
    AS
        SELECT Id , CategoryName
        FROM Categories
Run Code Online (Sandbox Code Playgroud)

在我运行这个方法的地方,我回到了reader.Close()一个说NullRefferenceException的异常.

我究竟做错了什么?

编辑

我刚注意到reader = cmd.ExecuteReader(); 抛出InvalidOperationException.这是因为查询?

Jus*_*ner 7

编写代码的方式意味着如果创建或连接错误SqlConnection,则finally块将尝试关闭reader尚未设置的代码.

检查finally块中的空值或重新构造代码.