C# Data Connections Best Practice?

后端 未结 2 444
攒了一身酷
攒了一身酷 2020-12-01 02:29

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?

相关标签:
2条回答
  • 2020-12-01 02:37

    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.

    0 讨论(0)
  • 2020-12-01 02:51

    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.

    0 讨论(0)
提交回复
热议问题