Resolved Establishing database connection with a using statement c#

Automation23

Member
Joined
Jul 13, 2022
Messages
7
Programming Experience
1-3
Hello everyone!

I have two separate methods that open the connection and close it. But I need to implement a using statement. How can I establish the connection with a ‘using’ statement, so then I can implement database methods, validate the results, and then close/dispose the connection?

Thank you in advance!
 
You can't use a using statement to open the connection, implement database methods, validate results. You can use a using statement to optionally instantiate a database connection, and then close and dispose the connection.

If you currently have two separate methods then there is no (easy) way to convert the to use a using statement. Now, on the other hand if you had two separate method calls then you can convert one of them to close the connection. You will still have to open the connection as a method call.

See example of code in SqlConnection documentation to see how using is used:
 
Last edited:
If you must absolutely open and close a SQL connection using a using statement, then you'll need to create a class that implements IDisposable that not only instantiates the SQL connection, but also opens it as part of its constructors, then disposes of the SQL connection when the class is disposed, and then finally in your using statement instantiate your custom class.

Be warned that there are some schools of thought in object oriented design which strongly believe that constructors should never throw exceptions because they don't do "real work" -- only simple initialization. I'll let you decide whether you subscribe to that design philosophy or not.
 
Back
Top Bottom