我刚刚学习使用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.这是因为查询?