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


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

Please guide me where m going wrong.


@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);        
  SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);   

(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


"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#

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#

1 Answered Questions

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

2 Answered Questions

[SOLVED] sql error running a select statement

3 Answered Questions

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

Sponsored Content