如何使用会话将数据库中的特定列数据显示到标签

本文关键字:数据 显示 标签 会话 何使用 数据库 | 更新日期: 2023-09-27 18:20:51

我有一个SQL Server数据库,其中有一个名为student的表,其列为:

  • std_id
  • 用户名
  • 密码
  • 年龄
  • 地址

场景是用户已经登录,并且他/她的username保存在会话中,而他正在导航标签。标签中应显示登录用户的年龄。

我不知道如何做到这一点,许多示例显示了如何在不使用WHERE子句或不使用会话的情况下将数据库中的数据放入标签。

这是我使用的代码,在本应显示年龄的页面上不起作用。

    Dim con As String = ConfigurationManager.ConnectionStrings("con").ConnectionString
    Dim mycon As New SqlConnection(con)
    Dim agequery As String
    mycon.Open()
    agequery = "select age from student where username='" + Session("user")
    Dim com As New SqlCommand(agequery, mycon)
    lbl_agecurrent.Text = CStr(com.ExecuteScalar)
    mycon.Close()

如何使用会话将数据库中的特定列数据显示到标签

我不确定这是否重要,但我通常在Session变量周围使用方括号。此外,您忘记了使用撇号来结束您的年龄查询语句。因此,当执行SQL语句时,它找不到匹配的用户名,因此会向标签返回一个null值,这意味着不会向用户显示任何内容。

如果我正确理解你的规范,我会写如下。

string ageQuery = "SELECT age FROM student WHERE username='" + Session["user"] + "'"
string connString = ConfigurationManager.ConnectionStrings("con").ConnectionString;
using (SqlConnection sqlConnection = new SqlConnection(connString))
using (SqlCommand sqlCommand = new SqlCommand(ageQuery, sqlConnection))
{
    sqlConnection.Open();
    lbl_agecurrent.Text = (com.ExecuteScalar).ToString();
}

如果您正在寻找有关此的更多信息,请查看http://www.dotnetperls.com/sqlconnection