sam
sam

Reputation: 13

How to display specific column data to a label from a database using a session?

I have a SQL Server database with a table called student and its columns are:

The scenario is that the user is already logged in and his/her username is saved in a session, while he is navigating a label should show the age of the logged user in a label.

I don't know how to do this, many examples shows how to put data from database to label without using WHERE clause or without using a session.

This is my code I used that didn't work from the page that is supposed to show the age.

    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()

Upvotes: 1

Views: 2022

Answers (1)

khinkle
khinkle

Reputation: 111

Im not sure if this matters, but I usually use square brackets around my Session variables. Also, you forgot an apostrophe to close your agequery statement. So when the SQL statement is executed, it can't find a matching username and therefore returns a null value to your label, meaning that nothing is displayed to your user.

If I understand your specifications correctly, I would write this as follows.

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

If you are looking for more information about this, check out http://www.dotnetperls.com/sqlconnection

Upvotes: 2

Related Questions