0

I have this tutorial about making a library system but code is like opening the Connection and then after a few codes and commands it ends with a Close(); method is it really a need to close the connection then open it again whenever there's a new function?

For example in Login button there's this code that starts with connnection.open(); and ends with connection.close(); then in Search Button there's also this Open and Close methods....

is it really necessary to close the connection? why not just let it open and then close it when the program terminates?

  • SQL connections, when open, represent a connection to the database. The connection class implements `IDisposable`, which means you should call `Dispose` on them when you are finished using them (or, better still use them in the context of a `using` statement). But, they aren't really database connections, they are database connection façades. When you close (or dispose) them, the associated connection goes back into a pool. When you create a new one, if there's a matching one in the pool, it gets used. So, yes, create, open, use, and quickly dispose your connections – Flydog57 Mar 15 '20 at 05:54
  • For the last part of the question: The process terminating will result in the connection being closed by the OS. The server will notice this and close the connection on its own end. However, **it’s recommend to be diligent and properly close resources in a controlled manner**. This ensures a valid program that does not run out of resources, regardless of how long it runs. – user2864740 Mar 15 '20 at 06:05

1 Answers1

0

The correct way to do that is with the using statement: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement

Y.L
  • 694
  • 12
  • 26