【问题标题】:.NET C# Web API INSERT.NET C# Web API 插入
【发布时间】:2021-08-02 12:52:32
【问题描述】:

我正在学习 Visual Studio 2019,我正在尝试使用 ASP.NET Web 应用程序 (.NET Framework) 构建 Web API。

我正在使用 Postman 将值发布到我的 SQL Server 数据库。

在我的 ValuesController 中,在 Post 下,我有以下内容:

public string Post([FromBody] string value)
{
  SqlCommand cmd = new SqlCommand("Insert Into Employees (Id,FirstName,LastName,email,userlevel) 
    VALUES ('"+value+"', '"+value+"', '"+value+"', '"+value+"', '"+value+"')", con);
  con.Open();
  int i = cmd.ExecuteNonQuery();
  con.Close();
  if(i == 1)
  {
    return "Record inserted with the value as " + value;
  }
  else
  {
    return "Try again";
  }
}

我运行应用程序并使用以下参数将 URL 粘贴到 Postman:

{
"Id": 10,
"FirstName": "Michael",
"LastName": "Jordan",
"email": "mjordan@goat.com",
"userlevel": 9
}

我得到以下输出:

"Record inserted with the value as "

记录已保存,但插入时 ID 为 0。所有其他字段均为空白。

我最初的 SqlCommand 编码是这样的:

SqlCommand cmd = new SqlCommand("Insert Into Employees (Id,FirstName,LastName,email,userlevel) 
  VALUES ('"+value+"')", con);

但我收到以下错误:

System.Data.SqlClient.SqlException: 'There are more columns in the INSERT statement than 
values specified in the VALUES clause. The number of values in the VALUES clause must match the number of 
columns specified in the INSERT statement.'

如何让 INSERT 查询正常运行,以便插入所有参数?

【问题讨论】:

  • parameterize your queries...不要将它们与您的原始值连接在一起...
  • VALUES ('"+value+"')" 这部分查询是什么?
  • [FromBody] 的模型绑定器适用于复杂类型,例如类。您应该为您的 POST 主体创建一个模型,以便它可以正确绑定,然后您可以将所有这些 value 替换为类的属性。
  • @AFarmanbar - 我不知道如何回答这个问题。我确实知道,如果我只用一列编写 INSERT 并使用单个值,查询就会运行并插入单个值(我希望这是有道理的)。
  • '"+value+"' 这只是一个字符串值,因为你用'包围它

标签: c# .net sql-server webapi


【解决方案1】:

当您发送对象时,您应该接收对象,而不是字符串。你可以声明这样的东西作为参数类型:

  public class UserDTO
  {
     public int Id { get; set; }
     public string FirstName { get; set; }
     public string LastName { get; set; }
     public string Email { get; set; }
     public int userlevel { get; set; }
  }

此外,从值中删除单引号,因为它会在您尝试插入字符串“值”时理解。 更好的是,正如 Broots 所说,参数化您的查询(查看 cmd .Parameters 集合)

您可以将类放在新文件 userDTO.cs 中 实现可能是这样的:

  public string Post([FromBody] userDTO user)
  {
     SqlCommand cmd = new SqlCommand(@"Insert Into Employees (Id,FirstName,LastName,email,userlevel) 
   
       VALUES(@Id,@FirstName,@LastName,@Email,@userlevel)", con);


     cmd.Parameters.Add(new SqlParameter("@Id", user.Id));
     cmd.Parameters.Add(new SqlParameter("@FirstName", user.FirstName));
     cmd.Parameters.Add(new SqlParameter("@LastName", user.LastName));
     cmd.Parameters.Add(new SqlParameter("@Email", user.Email));
     cmd.Parameters.Add(new SqlParameter("@userlevel", user.userlevel));

.......

【讨论】:

  • 我不知道把这门课放在哪里。抱歉,我还在学习中。
猜你喜欢
  • 2021-08-24
  • 2017-08-03
  • 1970-01-01
  • 1970-01-01
  • 2018-05-08
  • 2015-09-04
  • 1970-01-01
  • 2020-09-18
  • 2017-11-07
相关资源
最近更新 更多