Link to home
Start Free TrialLog in
Avatar of csetzkorn
csetzkorn

asked on

good practise of using command.ExecuteNonQuery()

Dear all,

I am just wondering whether it is a good practise to use several command.ExecuteNonQuery() invocations (for example) in one try/catch block?

Many thanks,

Christian
Avatar of mmarinov
mmarinov

Hi csetzkorn,

the use of ExecuteNonQuery is appropriate when you don't need to return anything from database, but just to execute the code and eventually to know how many records have been afexted. This method is commonly used when you delete records, or update records but you don't need to return the new information or some parameters because the ExecuteNonQuery will not gives you this information

Regards!
B..M
mmarinov
Avatar of csetzkorn

ASKER

Ok, I didn't nec. mean ExecuteNonQuery but also several ExecuteScalar(). Is it still ok to use several of these statements in one try/catch block?
csetzkorn,

it is not a problem. actually if i have such a situation i try to optimize the functionality and do all of the things within one call to the database. But if you don't want or you can not do it - go with several.
The one problem that you can receive is when an error arise it will be hard to debug if your calls are near to execution results and you will have to step-by-step to understand where the problem arises

Regards!
B..M
mmarinov
Yeah, thanks I thought about this. The problem is that I sometimes obtain a:

Commands out of sync; You can't run this command now

However this seems to be realeted to datareaders.

Thanks.

Chris
Hi,
Did you mean that you want to use something like this :

Try
'ExecuteNonQuery1
'ExecuteNonQuery2
Catch e as Exception

Finally
csetzkorn,

if you use datareader i don't think you can work with 2 datareader within one connection
for the ExecuteScalar() may be ( i haven't gone through this ) you have to open/close the connection - which can slow down the performance

Regards!
B..M
mmarinov
I am currently using a reader twice (I close it before I use it again).
ASKER CERTIFIED SOLUTION
Avatar of mmarinov
mmarinov

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial