user3206753
user3206753

Reputation: 25

Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near '='

I created simple asp.net c# web page that shows the name of the user who logged in, it works fine but the problem is when I leave the page open for a while and I refresh it or click any button on it it gives me an error and I have to go back to the login page and login again to make the error go, this error message:

Incorrect syntax near '='. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near '='.

Source Error:

Line 22: 
Line 23:         conn.Open();
Line 24:         SqlDataReader DR1 = cmd.ExecuteReader();
Line 25:         if (DR1.Read())

here is my code:

    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
    SqlCommand cmd = new SqlCommand("select * from usersTable where user_id = "+ Session["userIdSession"], conn);

    conn.Open();
    SqlDataReader DR1 = cmd.ExecuteReader();
    if (DR1.Read())
    {
        Label1.Text = DR1.GetValue(1).ToString();

    }
    else
    {
        conn.Close();
    }
    }

Upvotes: 0

Views: 1702

Answers (1)

Rahul Singh
Rahul Singh

Reputation: 21795

Prooblem with your code is that if Session["userIdSession"] is null your query will be like this:-

select * from usersTable where user_id = 

Which is obviously an invalid SQL query. Use parametrized query and check if Session["userIdSession"] has some value before executing.

You should first check if Session["userIdSession"] has some value like this:-

if(Session["userIdSession"] != null)
{
     //execute your code
}

Also, use parametrized query to avoid SQL Injection attacks:-

SqlCommand cmd = new SqlCommand("select * from usersTable where user_id = @UserId", conn);
cmd.Parameters.Add("@UserId",SqlDbType.Int).Value = Convert.ToInt32(Session["userIdSession"]);

Also, consider using the using statement to automatically dispose expensive objects like connections.

Upvotes: 1

Related Questions