存储过程需要未提供的参数id值



我有一个学生表,列为

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";
}

在用数据填写表格后,点击ADD按钮,它应该将数据添加到表格中,但它给了我一个错误,说:

存储过程需要未提供的参数id值。

我尝试将id设置为自动递增值。并从表单中删除了id字段。这一次,当我按下添加按钮时,它表示存储过程需要未提供的firstname值。

错误在哪里?

谢谢。

存储过程中的插入命令可能缺少id。

如前所述,您最好在这里使用强类型转换。

并且如前所述paramaters.Add在这里是优选的。

using (SqlCommand cmd = new SqlCommand("spAddStudents", con))
{
cmd.Parameters.Add("@id", SqlDbType.Int).Value = txtId.Text;
cmd.Parameters.Add("@firstname", SqlDbType.NVarChar).Value = txtFirstName.Text;
. etc .etc .etc
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}

请注意我们是如何强制执行命令类型的——也许可以尝试一下。我认为问题出在存储过程代码中。

最新更新