连接代码中的异常

时间:2011-04-24 13:26:35

标签: asp.net

我正在尝试从Web表单连接到sql server,但在代码中获得了错误的语法异常。

protected void Button1_Click(object sender,EventArgs e)         {

SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings [“HRMSConnectionString1”]。ToString());

  {
      SqlCommand cmd = new SqlCommand("select * from persons where User_Id="+uid.Text+"and Password!="+pswd.Text, cn);

      cn.Open();

      SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);   //exception in this line

      rdr.Read();

      Response.Write(rdr[0].ToString()); 
  }

}

请指导我哪里出错。

3 个答案:

答案 0 :(得分:0)

数据库希望看到字符串周围的引号:

"select * from persons where User_Id='"+uid.Text+"'and Password!='"+pswd.Text+"'"

答案 1 :(得分:0)

尝试:

"Select * from persons where [User_Id] ='"+uid.Text+"'and [Password] <> '"+pswd.Text + "'"

另外:Protect your parameters!这是必须的,以防止SQL注入。

答案 2 :(得分:0)

看起来您正在使用此!= 运算符来表示Not-Equal,但这是在编程语言中。对于Sql,您需要使用&lt;&gt; 运算符

看起来你正在使用带有+的SQL查询,在任何情况下都必须避免使用。

所以你的最终代码(粗略)看起来应该是这样的

  SqlCommand cmd = new SqlCommand("select * from persons where User_Id='@userid'
  and Password<>'@password'",cn);        
  cmd.Parameters.Add(@userid,uid.Text);
  cmd.Parameters.Add(@password,pswd.Text);
  cn.Open();        
  SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);   
  rdr.Read();        
  Response.Write(rdr[0].ToString()); 

(另外我不确定这个查询的目的是什么,但你提取*然后只使用一个值。如果你只想检查一个值,你可以使用像

这样的查询
Select count(1) from persons where User_Id='@userid' and Password<>'@password'

然后将其与ExecuteScalar方法一起使用。只是一个建议。