I’m working on a C# project. and my program works with SQL Server.
Which of the below approaches is correct?
-
I open a SQL Server connection when I start my program and when I close my program the SQL connection closes too.
-
I open a SQL Server connection when I need to work with SQL and close it when my work is done.
You tell us. BOTH are correct. One is bad practice, one is good practice for normal situations, but technically both work.
Depends on context. NORMALLY you would use 2 only – this has a lot of Advantages, for example not having to deal with ocnnections being reset when the Server goes down or some seconds. It also means you can easily go multiu threaded and use multiple connetions – a moment that Comes earlier rather than later and when most junoir developer realize they would rather do something else as it gets complex then.
And this is TOTALLY NOT A C# question. It is a General “how to use a database” for the last 20 years, in every langauge with every database I have ever used.