你如何从SqlDataReader中获取值?

时间:2016-04-27 07:48:05

标签: c# sql stored-procedures

我有一个返回列表的存储过程,但是如何将结果放入C#中的列表?

 using(SqlConnection sqlConnectionString = new SqlConnection(ConfigurationManager.ConnectionStrings["EfenKaConnectionString"].ConnectionString))
 using(SqlCommand cmd = new SqlCommand("SP_ListMonths", sqlConnectionString))
 {
     SqlDataReader reader;
     cmd.CommandType = CommandType.StoredProcedure;

     cmd.Parameters.Add("@MONTH", SqlDbType.Int).Direction = ParameterDirection.Output;

     sqlConnectionString.Open();

     cmd.ExecuteNonQuery();

     int defualtMonth = Convert.ToInt32(cmd.Parameters["@MONTH"].Value);
     reader = cmd.ExecuteReader();
     sqlConnectionString.Close();
 }

如何从阅读器访问值?

enter image description here

1 个答案:

答案 0 :(得分:1)

不要致电cmd.ExecuteNonQuery(); 试试这个

    SqlDataReader reader = command.ExecuteReader();

    while (reader.Read())
    {
        object obj1 = reader["ColumnName1"];
        object obj2 = reader["ColumnName2"];  
        object obj3 = reader["ColumnName3"];
    }