使用带有存储过程的C#从sql数据库中检索数据

时间:2013-02-01 19:59:54

标签: c# asp.net sql-server stored-procedures

每当我尝试从数据库中检索数据时,我都会变为空。我正在使用的代码如下:

protected void Button2_Click(object sender, EventArgs e)
 {
    SqlConnection myConnection = new SqlConnection(GetConnectionString());
    SqlCommand cmd = new SqlCommand("spSelectCustomer", myConnection);
    cmd.CommandType = CommandType.StoredProcedure;
    myConnection.Open();

    SqlParameter custId = cmd.Parameters.Add("@CustomerId", SqlDbType.Int);
    custId.Direction = ParameterDirection.Input;
    custId.Value = 10;

    SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

    Label1.Text = dr["FirstName"].ToString();
    Label2.Text = dr["LastName"].ToString();
    Label3.Text = dr[3].ToString();
    Label4.Text = dr["Email"].ToString();
}
private static string GetConnectionString()
{
    return ConfigurationManager.ConnectionStrings["Lab3ConnectionString"].ConnectionString;
}

4 个答案:

答案 0 :(得分:7)

您需要先致电Read才能访问数据,您的代码应为

While (dr.Read())
{

    Label1.Text = dr["FirstName"].ToString();
    Label2.Text = dr["LastName"].ToString();
    Label3.Text = dr[3].ToString();
    Label4.Text = dr["Email"].ToString();
}

//close DataReader
dr.Close();

答案 1 :(得分:2)

您在阅读器上错过了对Read()的来电。我还建议您将IDisposable个对象包装在using语句中,如下所示。

SqlDataReader检索您的值时,您似乎也在使用列名和序号位置的奇怪组合。

protected void Button2_Click(object sender, EventArgs e)
{
    using (SqlConnection myConnection = new SqlConnection(GetConnectionString()))
    {
        using (SqlCommand cmd = new SqlCommand("spSelectCustomer", myConnection))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            myConnection.Open();

            SqlParameter custId = cmd.Parameters.AddWithValue("@CustomerId", 10);

            using (SqlDataReader dr = cmd.ExecuteReader())
            {
                if (dr.Read())
                {
                    Label1.Text = dr["FirstName"].ToString();
                    Label2.Text = dr["LastName"].ToString();
                    Label3.Text = dr[3].ToString();
                    Label4.Text = dr["Email"].ToString();
                }
            }
        }
    }
}

答案 2 :(得分:1)

在从DataReader读取列值之前,必须从数据读取器调用Read()方法。

if (dr.Read())
{
    Label1.Text = dr["FirstName"].ToString();
    Label2.Text = dr["LastName"].ToString();
    Label3.Text = dr[3].ToString();
    Label4.Text = dr["Email"].ToString();
}

您也可以尝试:

SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.SingleRow);

答案 3 :(得分:0)

SqlDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
while(myReader.Read()) 
{
Console.WriteLine(myReader.GetString(0));
}
myReader.Close();

//隐式关闭连接,因为指定了CommandBehavior.CloseConnection。

文档: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executereader(v=vs.71).aspx