ExecuteNonQuery always returns zero. Can i use thi

2019-07-31 16:26发布

问题:

I am creating a oracle user in dba_users table by using the below c# code where i am using oledbcommand and ExecuteNonQuery. User is being successfully created in the dba_users table but ExecuteNonQuery is always retun value as "0"

So i am doing validation in my code as (IsUserCreated==0). Am i correct with my coding here?

int IsUserCreated= oleCreateUserCommands.ExecuteNonQuery();

if(IsUserCreated==0)
{
//TBD code
Response.write("User Created Successfully");
}

else
{
//TBD Code
Response.write("User creation failed with some error");
}

回答1:

No, basically. That 0 doesn't mean much - in fact, the main thing it tells me is that you probably have SET NOCOUNT ON somewhere, or this is a sproc without a RETURN - otherwise I would expect 1 to be returned to indicate 1 row impacted. Either way: it does not indicate the lack of an error. The lack of an exception indicates the lack of an error. Returning 1 is useful as a "yes, exactly 1 row was updated" check, if it is enabled.



回答2:

As Marc said, you can't rely on the return value. The return value is actually not consistent or portable, across different databases and statement types you may see -1 or 0 for success for non-DML, and 0, 1 or greater for DML, in my experience. Per his comment about SET NOCOUNT ON, Oracle doesn't support that, its a SQL Server feature.

Incidentally, for a CREATE USER statement, I always see -1 (I develop several desktop database tools and I've done a lot of tracing) though I don't use OleDb much. I am surprised you see 0, you should double check.

Regardless, you must use exceptions to handle error cases for ExecuteNonQuery and ExecuteScalar and its siblings. It is not possible to write robust code otherwise. The lack of exception implies success. As far as the return code, it is really useless for validation, except in DML. How do you write a generic algorithm that can accept -1, 0 or 1, or N as valid? I simply check it when I know I issue a possible DML, and need to return the row count to the user.

  1. Your code should be in a using block (all IDisposable types in ADO should typically be disposed in a using statement)
  2. You should have a try/catch or at least a try/finally

If you don't like repeating yourself, then wrap ExecuteNonQuery in your own function that will handle exception and return a bool true/false. In certain cases, I like to write extension methods for the connection or reader classes.