【发布时间】:2021-07-14 04:03:21
【问题描述】:
我有一张带列的学生表
id primary key, firstname, lastname, birthdate, gender, phone, address.
我正在使用 ASP.NET 中的 WebForms。
我有这个存储过程。
create procedure spAddStudents
(
@id int
, @firstname nvarchar(50)
, @lastname nvarchar(50)
, @birthdate date
, @gender nvarchar(5)
, @phone nvarchar(50)
, @address nvarchar(200)
)
as
Begin
insert into students
values (@id, @firstname, @lastname, @birthdate, @gender, @phone, @address)
End
在网络表单中我写了这段代码
SqlCommand cmd = new SqlCommand("spAddStudents",con);
cmd.Parameters.AddWithValue("@id",txtId.Text);
cmd.Parameters.AddWithValue("@firstname",txtFirstName.Text);
cmd.Parameters.AddWithValue("@lastname",txtLastName.Text);
cmd.Parameters.AddWithValue("@birthdate",txtBirthDate.Text);
cmd.Parameters.AddWithValue("@gender",ddlGender.SelectedValue);
cmd.Parameters.AddWithValue("@phone",txtPhone.Text);
cmd.Parameters.AddWithValue("@address",txtAddress.Text);
con.Open();
int k = cmd.ExecuteNonQuery();
if (k != 0)
{
lblMessage.Text = "Record inserted successfully";
}
在点击添加按钮时用数据填充表单后,它应该将数据添加到表中,但它给了我错误提示:
存储过程需要未提供的参数 id 值。
我尝试将 id 设为自动增量值。并从表单中删除了 id 字段。这次当我按下添加按钮时,它表示存储过程期望未提供名字的值。
错在哪里?
谢谢。
【问题讨论】:
-
嗨@LMS,建议不要使用
.AddWithValue()作为您为@id传入的存储过程和SqlParameter 中的数据类型不匹配。您可以阅读此article。谢谢。 -
还有更多的最佳实践,不要在你的 SP 前面加上 sp。而且您应该始终列出要插入的列。您需要在 Execute 命令上暂停调试器并检查您的参数值(在删除 AddWithValue 之后)。
-
在 c# 中,您将所有变量转换为文本。如果它们来自文本框,则执行以下操作: int.Parse(txtId.Text)
标签: c# asp.net sql-server