SqlException:','附近的语法不正确

时间:2020-07-13 20:23:13

标签: asp.net sql-server asp.net-mvc azure

我找不到语法有问题的地方

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

我不明白-我的语法错误是什么? connstr是我的连接字符串,Correctornot是从button接收到的值,即按钮值

3 个答案:

答案 0 :(得分:1)

如果Response的类型为varchar / string,则需要用'括起来:

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

说您确实应该将参数用作最佳实践

答案 1 :(得分:1)

您需要在第二个参数值周围添加单引号以解决此问题

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

但是,除了该代码易于进行sql注入攻击外,如果Correctornot变量中的文本本身具有单引号并且很大,则该代码仍将失败

check this来查看如何参数化查询的示例代码

答案 2 :(得分:1)

请尝试

SqlCommand cmd = new SqlCommand("INSERT INTO [dbo].[Labeler_Email_For_Confirmation_Agents] (Id, Response) VALUES (" +  TempData["id"].ToString + "  ,  " + Correctornot.ToString + ");");
相关问题