SQL Server asp.net 'The multi-part identifier "abc@gmail.com" could not be bound.'

omvjsjqw  于 2023-08-02  发布在  .NET
关注(0)|答案(2)|浏览(101)

I wrote some code to access the id form table dbo.details by using user email id stored in session, but I get this error
The multi-part identifier "abc@gmail.com" could not be bound

I have used the built-in server of Visual Studio 2017.

This is my code:

protected void Page_Load(object sender, EventArgs e)
{
        if (Session["user"] == null)
        {
            Response.Write("<script>alert('you have to login to Checkout!')</script>");
            Response.Redirect("login.aspx");
        }
        else
        {
            string S1 = Convert.ToString(Session["user"].ToString());

            SqlConnection scon = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
            String myquery = "select ID from dbo.details where email=" + S1;

            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = myquery;
            cmd.Connection = scon;

            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = cmd;

            DataSet ds = new DataSet();
            da.Fill(ds);

            int details_id = Convert.ToInt32(ds.Tables[0].Rows[0][0].ToString());
            Response.Write(details_id);
        }
}

I have checked all the names and they are ok.

I don't know what to do now!

vlju58qv

vlju58qv1#

Use string.Format() method with string quotation mark

string _user= Convert.ToString(Session["user"].ToString());

String SQL = string.Format("select ID from dbo.details where email='{0}'", _user);
wydwbb8l

wydwbb8l2#

The root cause of the error is this line -

String myquery = "select ID from dbo.details where email=" + S1;

it will build the query as

select ID from dbo.details where email=abc@gmail.com;

Now if you run this query, you will get exception as email is suppose to be string enclosed in single quotes. So change your myQuery to add single quotes around email like below .

String myquery = "select ID from dbo.details where email='" + S1 + "'";

But, its always recommended to use parameterised queries. to avoid SQL injections.

相关问题