我是c#的新手并且在将数据表单插入数据库时遇到问题。以下是类和过程定义的代码。当我按下按钮Save(btnSaveUser)
时,它会显示错误消息
处理请求时发生了一些错误
当数据插入数据库时是否显示错误消息。
btnSaveUser
代码:
private void btnSaveUser_Click(object sender, EventArgs e)
{
try
{
int result = uc.ManageUser(txtFullName.Text, txtAddress.Text, txtPhone.Text, txtEmail.Text, Convert.ToDateTime(dateTimePickerJoinedDate.Text), txtUserame.Text, txtPassword.Text, Convert.ToDateTime(dateTimePickerCreatedDate.Text), "I");
if (result == 1)
{
MessageBox.Show("New User Saved");
dgvUserDetails.DataSource = uc.SelectAllUsers();
//MakeFieldsBlank();
}
else
{
MessageBox.Show("SOME ERRORS OCCURRED WHILE PROCESSING THE REQUEST");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
UserClass.cs
:
public class UserClass
{
SqlConnection conn = new SqlConnection(DataConnectionClass.DbConnection);
public int ManageUser(String Name, String Address, String Phone, String Email, DateTime JoinedDate, String Username, String Password,DateTime CreatedDate,String Mode)
{
try
{
int result = 0;
SqlCommand cmd = new SqlCommand("sp_ManageUser", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@StaffID",DBNull.Value);
cmd.Parameters.AddWithValue("@Name", Name);
cmd.Parameters.AddWithValue("@Address", Address);
cmd.Parameters.AddWithValue("@Phone", Phone);
cmd.Parameters.AddWithValue("@Email", Email);
cmd.Parameters.AddWithValue("@JoinedDate", JoinedDate);
cmd.Parameters.AddWithValue("@Username", Username);
cmd.Parameters.AddWithValue("@Password", Password);
cmd.Parameters.AddWithValue("@CreatedDate", CreatedDate);
cmd.Parameters.AddWithValue("@Mode", Mode);
conn.Open();
result = cmd.ExecuteNonQuery();
conn.Close();
return result;
}
catch (Exception ex)
{
throw ex;
}
}
程序定义:
ALTER PROCEDURE [dbo].[sp_ManageUser]
@StaffID int,
@Name nvarchar(100),
@Address nvarchar(500),
@Phone nvarchar(100),
@Email nvarchar(100),
@JoinedDate date,
@Username nvarchar(50),
@Password nvarchar(max),
@CreatedDate date,
@Mode varchar(1)
AS
BEGIN
SET NOCOUNT ON;
-- Insert statements for procedure here
if(@Mode='I')
insert into tbl_Staff (Name, Address, Phone, Email, JoinedDate, Username, Password, CreatedDate)
values(@Name, @Address, @Phone, @Email, @JoinedDate, @Username, @Password, @CreatedDate)
if(@Mode='U')
Update tbl_Staff
set Name = @Name,
Address = @Address,
Phone = @Phone,
Email = @Email,
JoinedDate = @JoinedDate,
Username = @Username,
Password = @Password,
CreatedDate = @CreatedDate
where
StaffID = @StaffID
if(@Mode='D')
Delete from tbl_Staff
where StaffID = @StaffID
end
答案 0 :(得分:1)
UserClass.ManageUser()
返回SqlCommand.ExecuteNonQuery()
的结果,返回受影响的行数。查看存储过程,它执行SET NOCOUNT ON
,它将停止返回受存储过程影响的行数。这就解释了为什么你会看到这条消息。
尝试注释掉SET NOCOUNT ON
,这应该允许返回插入的行数。
答案 1 :(得分:0)
此:
ExecuteNonQuery() returns -1 when execute the stored procedure
表示存储过程的返回值始终为-1。
你检查过它实际返回的是什么吗?如果它总是返回-1那么你总会得到一条错误信息。