Ok, so this is one of those kind of opinionated topics, but based on your knowledge, opinion, and current practice, what is the best way to set the following scenario up?
I think it's better to just open them upon the application launching, since you need stuff from your database right?I'm not an expert in this, it's just my opinion... I programmed some similar applications and made the connection at the start of the main form. The only form where i created a separate connection was the login form.
Connections are pooled by .NET, so re-creating them generally isn't an expensive operation. Keeping connections open for long periods of time, however, can cause issues.
Most "best practices" tell us to open connections as late as possible (right before executing any SQL) and closing them as soon as possible (right after the last bit of data has been extracted).
An effective way of doing this automatically is with using
statements:
using (SqlConnection conn = new SqlConnection(...))
{
using(SqlCommand cmd = new SqlCommand(..., conn))
{
conn.Open();
using(DataReader dr = cmd.ExecuteReader()) // or load a DataTable, ExecuteScalar, etc.
{
...
{
}
}
That way, the resources are closed and disposed of even if an exception is thrown.
In short, opening a connection when the app opens or when each form opens is probably not the best approach.