-2

I am not able to find what is wrong with my syntax:

SqlConnection conn = new SqlConnection(connstr);
conn.Open();
            
SqlCommand cmd = new SqlCommand("INSERT INTO [dbo].[Labeler_Email_For_Confirmation_Agents] (Id, Response) VALUES (" +  TempData["id"] + "  ,  " + Correctornot + ");");

cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = conn;

cmd.ExecuteReader();

I don't understand - what is my syntax error? connstr is my connection string and Correctornot is the value received from button , i.e button value

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
crazysra
  • 111
  • 10

3 Answers3

1

If Response is of type varchar/string you need to surround the value with ' :

SqlCommand cmd = new SqlCommand(" INSERT INTO [dbo].[Labeler_Email_For_Confirmation_Agents] ( Id , Response ) VALUES ( " +  TempData["id"] + "  ,  '"+ Correctornot + "'  );" );

Saying that you should really be using parameters as best practice

Aman B
  • 2,276
  • 1
  • 18
  • 26
1

you need to add single quote around second parameter value to fix this

SqlCommand cmd = new SqlCommand(" INSERT INTO [dbo].[Labeler_Email_For_Confirmation_Agents] ( Id , Response ) VALUES ( " +  TempData["id"] + "  ,  '"+ Correctornot + "'  );" );

But, apart from the fact that this code is open to sql injection attack, this code will still fail if text in Correctornot variable itself has single quote and is a big NO-NO

check this to see sample code of how you can parameterised query

Kedar
  • 147
  • 5
1

Please try

SqlCommand cmd = new SqlCommand("INSERT INTO [dbo].[Labeler_Email_For_Confirmation_Agents] (Id, Response) VALUES (" +  TempData["id"].ToString + "  ,  " + Correctornot.ToString + ");");
Anil
  • 13
  • 5