C#存储过程检查是否成功

C#存储过程检查是否成功

问题描述:

我有一个存储过程,它插入,删除或更新我的数据库中的行,并不返回任何值。我从我的C#代码调用它是这样的:C#存储过程检查是否成功

DAL.CDataContext dc = new DAL.CDataContext(); 
dc.MySproc(); 

如何检查它是否成功运行?

+0

什么是你'CDataContext()',你叫什么'MySproc()'。无论如何,你可以尝试'executenonquery':https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery(v=vs.110).aspx – Jacky

+0

如果它没有抛出,它运行成功。也许你的意思是别的吗?不插入或不更新不是失败。 –

+0

如果失败,你不会得到一个异常吗?所以如果你没有得到例外,那一定是成功的......我只是在猜测 – musefan

使用try catch。如果没有异常,那么查询成功运行,那么如果sucess返回true,返回false,如果它不是 例如

public static bool InsertObFile(PreApprove p) 
{ 
    var command = new SqlCommand(); 
    command.CommandText = "ObInsertPreApprove"; 
    command.CommandType = CommandType.StoredProcedure; 

    command.Parameters.AddWithValue("@EmployeeAutoId", p.EmployeeAutoId).Direction = ParameterDirection.Input; 
    command.Parameters.AddWithValue("@EmployeeId", p.EmployeeId).Direction = ParameterDirection.Input; 
    command.Parameters.AddWithValue("@DateFrom", p.DateFrom).Direction = ParameterDirection.Input; 
    command.Parameters.AddWithValue("@DateTo", p.DateTo).Direction = ParameterDirection.Input; 
    command.Parameters.AddWithValue("@Description", p.Description).Direction = ParameterDirection.Input; 
    command.Parameters.AddWithValue("@CreateUserId", p.CreateUserId).Direction = ParameterDirection.Input; 

    try 
    { 
     SqlHelper.ExecuteNonQuery(command); // this is where I run my stored procedure 
     return true; 
    } 
    catch (Exception e) 
    { 

     return false; 
    } 

} 
+1

但请(至少)记录异常。不,你只知道发生了一些错误,但没有详细信息。 –