Establishing database connection in c#

Hello everyone!

I have two separate methods that open the connection and close it. But I need to impplement 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 may not find a lot of database experts on this site. Maybe a better question for C# board:

1 Like

Thank you very much!

UPDATE: If anyone still facing with this issue, here is a response from another source:

" 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.

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."