7

每当我尝试从我的数据库中检索数据时,我总是得到空值。我正在使用的代码如下:

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

4 回答 4

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();
于 2013-02-01T20:03:29.577 回答
2

在从 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);
于 2013-02-01T20:01:51.410 回答
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();
                }
            }
        }
    }
}
于 2013-02-01T20:06:33.830 回答
0
SqlDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
while(myReader.Read()) 
{
Console.WriteLine(myReader.GetString(0));
}
myReader.Close();
//Implicitly closes the connection because CommandBehavior.CloseConnection was specified.

文档:SqlCommand.ExecuteReader 方法

于 2013-02-01T20:04:55.310 回答