in c# global connection to be used in all classes

后端 未结 5 1924
萌比男神i
萌比男神i 2021-01-22 18:59

I\'ve a connection string saved to Properties.Settings.Default, i need to use an sql connection in all classes without having to declare it everytime, so how should

5条回答
  •  我在风中等你
    2021-01-22 19:09

    I've have something similar set up in an old project like so. It's worth noting that you should always be using a new SqlConnection for all your operations, because of connection pooling.

    public static class SqlConnectionUtil
    {
        public static string DefaultConnectionString { get; private set; }
    
        static SqlConnectionUtil()
        {
            SqlConnectionUril.DefaultConnectionString = 
                    Properties.Settings.Default.TheConnectionString;
        }
    
        public static SqlConnection Create()
        {
            return new SqlConnection(SqlConnectionUtil.DefaultConnectionString);
        }
    }
    

    You would then use it like this.

    using (var connection = SqlConnectionUtil.Create())
    {
        using (var command = connection.CreateCommand())
        {
            // do things.
        }
    }
    

提交回复
热议问题