gpt4 book ai didi

c# - 使用C#和存储过程从sql数据库中检索数据

转载 作者:太空狗 更新时间:2023-10-29 21:13:33 30 4
gpt4 key购买 nike

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

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;
}

最佳答案

你需要先调用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();

关于c# - 使用C#和存储过程从sql数据库中检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14654064/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com