By vatspoo


2011-04-24 13:26:34 8 Comments

I am trying to connect to a SQL server from a web form but getting an incorrect syntax exception in the code.

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

Please guide me where m going wrong.

3 comments

@Subhash Dike 2011-04-25 08:40:41

Looks like you are using this != operator for the purpose of Not-Equal, however that's in the progamming language. For Sql, you need to use <> operator

Also looks like you are using sql query with + which must be avoided under any cicumstances.

So your final code (in rough) should look like this

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

(Also I am not sure what is the purpose of this query, but you are fetching * and then only using one value. If you just want to check one value, you can use query like

Select count(1) from persons where User_Id='@userid' and Password<>'@password'

and then use it with ExecuteScalar method. Just a suggestion.

@user492238 2011-04-24 13:29:55

Try:

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

Also: Protect your parameters! This is a must in order to prevent against SQL injection.

@Christo 2011-04-24 13:29:43

The database wants to see quotes around the strings:

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

Related Questions

Sponsored Content

4 Answered Questions

[SOLVED] ASP.Net insert data from Textbox to a database

2 Answered Questions

[SOLVED] error after clicking submit button

  • 2016-03-21 11:07:52
  • sweta tatkare
  • 73 View
  • 1 Score
  • 2 Answer
  • Tags:   java c# asp.net

2 Answered Questions

[SOLVED] Export data with images to Excel

1 Answered Questions

[SOLVED] Array of textbox and labels how to get value in submit method in c#

  • 2014-07-23 07:38:24
  • Rocky
  • 1906 View
  • 1 Score
  • 1 Answer
  • Tags:   c# asp.net

1 Answered Questions

[SOLVED] Error msg "Incorrect syntax near the keyword 'from' "

2 Answered Questions

[SOLVED] asp.net sql error running a select statement

3 Answered Questions

[SOLVED] Can't activate message box with SQL data - ASP.NET

Sponsored Content