【发布时间】: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