C# asp.net“多部分标识符”abc@gmail.com“无法约束。”
我编写了一些代码,通过使用会话中存储的用户电子邮件id来访问id表单表dbo.details,但是我得到了这个错误 多部件标识符abc@gmail.com无法约束 我使用了Visual Studio 2017的内置服务器 这是我的代码:C# asp.net“多部分标识符”abc@gmail.com“无法约束。”,c#,sql,asp.net,sql-server,C#,Sql,Asp.net,Sql Server,我编写了一些代码,通过使用会话中存储的用户电子邮件id来访问id表单表dbo.details,但是我得到了这个错误 多部件标识符abc@gmail.com无法约束 我使用了Visual Studio 2017的内置服务器 这是我的代码: protected void Page_Load(object sender, EventArgs e) { if (Session["user"] == null) { Response.Write("&
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);
}
}
我检查了所有的名字,他们都很好
我不知道现在该怎么办 错误的根本原因是这一行-
String myquery = "select ID from dbo.details where email=" + S1;
它将按照以下方式构建查询:
select ID from dbo.details where email=abc@gmail.com;
现在,若您运行这个查询,您将得到异常,因为假定电子邮件是用单引号括起来的字符串。因此,更改myQuery,在电子邮件周围添加单引号,如下所示
String myquery = "select ID from dbo.details where email='" + S1 + "'";
但是,始终建议使用它来避免SQL注入。不要使用易于SQL注入的代码,问题会“自行解决”。搜索C SQL参数并相应地更新代码。构建字符串时,需要将电子邮件括在单引号中。但即使这样也不是个好主意,您应该使用参数化查询。有关发生这种情况的原因以及如何避免这种情况的详细信息在SOL Parameters中给出了非常有效的。@MuratCanOĞUZHAN确信您可以采用这种方法,但如果不帮助某人解决这样一个大问题,只会延续那种真正可怕的编码风格。如果您进行演示,这将是一个更好的答案如何使用参数,而不是演示最糟糕的sql编写方法。都和这个问题有关…想知道为什么答案被否决了,我解释了OP获得异常的原因,并提供了解决问题的选项,包括通过共享链接推荐的方法,该链接对使用参数化查询有很好的解释。这不是我的否决票,但如果您添加2-3行代码来演示参数,则值得进行表决。