My question might be silly or may not be a question at all, but here it goes..
I am performing quite some database operations in my ASP.net MVC project where I am creating two objects each and every time namely, SqlConnection
and SqlCommand
.
I have shown an example below
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand("sRegisterUser", connection))
{
I am doing all these different operations inside one class under different methods.
My question is how can I reduce the creation of these objects each and every time? How can I create them globally
PS: sRegisterUser is a stored procedure, like wise other methods use different procedures which gets different values as parameters.
Please help me out.
Thanks for any help in advance.
The answer is, don't. You do not want to share these objects, you are using them appropriately.
You don't. You either keep the object alive, which is bad. Or you dispose it the way you should, and currently do.
So, why do you have use using
?
Since using
is necessary for disposing the handles in Windows.
You could also write this, which is similar to using using
:
SqlConnection connection = new SqlConnection(connectionString);
connection.Close();
connection.Dispose();
using
also disposes when the code above throws an error. Using using
is actually the shortest way to code this.
So the error-save version should be:
SqlConnection connection;
try
{
connection = new SqlConnection(connectionString);
...
connection.Close();
}
finally
{
connection.Dispose();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With