C# 如何从label中的数据库检索数据

C# 如何从label中的数据库检索数据,c#,C#,我想从数据库中检索学生ID。这是我的代码,我已经尝试过了,但它没有显示任何内容。 谢谢 protected void Button2_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection("Data Source=DESKTOP-Q69PRF4;Initial Catalog=new;Integrated Security=True"); if (con.State

我想从数据库中检索学生ID。这是我的代码,我已经尝试过了,但它没有显示任何内容。 谢谢

protected void Button2_Click(object sender, EventArgs e)
{

        SqlConnection con = new SqlConnection("Data Source=DESKTOP-Q69PRF4;Initial Catalog=new;Integrated Security=True");


        if (con.State == ConnectionState.Open)
        {
            con.Close();
        }
        con.Open();
        string str = "select * from StRecords where StID='" + Session["login"] + "'";
        SqlCommand com = new SqlCommand(str, con);
        SqlDataAdapter da = new SqlDataAdapter(com);
        DataSet ds = new DataSet();
    DataTable dt = new DataTable();
        da.Fill(dt);
    if (dt.Rows.Count > 0)
    {
        Label11.Text = dt.Rows[0]["StID"].ToString();

    }


    }

如果只想从数据库中获取
StudentId
,则只需选择该列并使用
ExecuteScalar
属性即可

代码

protected void Button2_Click(object sender, EventArgs e)
{
    using (SqlConnection con = new SqlConnection("Data Source=DESKTOP-Q69PRF4;Initial Catalog=new;Integrated Security=True"))
    {
        con.Open();
        string str = "select [StID] from StRecords where StID = @stdId;";
        using (SqlCommand com = new SqlCommand(str, con))
        {
            com.Parameters.AddWithValue("@stdId", Session["login"]);
            Label11.Text = com.ExecuteScalar().ToString();
        }
    }
}
还应始终使用参数,而不是以单引号传递值,以避免SQL注入攻击


还要尝试在
Web.Config
文件中提供连接字符串。

您没有执行命令,请尝试:SqlDataReader=command.ExecuteReader();而(reader.Read()){}@RadinGospodinov
da.Fill(dt)会话[“登录”]
应该有一些值。是的,它有一些值。@RadinGospodinov我也使用过它,但它给出了一个错误“当没有数据时无效”或。“对象引用未设置为对象的实例”它给出了一个错误。“对象引用未设置为对象的实例”@在这种情况下,似乎没有返回值-您应该调试并检查
会话[“login”]
是否具有有效值,并且该值也存在于您的数据库中