【问题标题】:Can I use same SQL connection string multiple times in my application?我可以在我的应用程序中多次使用相同的 SQL 连接字符串吗?
【发布时间】:2016-04-11 21:38:06
【问题描述】:

我是 SQL 新手。我正在使用 C# 构建应用程序,它使用本地 SQL Server 来读取/写入数据。我只有一个数据库,当我连接到 SQL Server 时,连接字符串总是一样的。

我的项目应用程序中有 9 个 Windows 窗体,每个窗体都使用相同的连接字符串,在某些窗体中,我多次使用相同的连接。我可以以相同的形式多次使用相同的连接字符串吗?谢谢你

这是连接字符串:

SqlConnection cn = new SqlConnection(@"Data Source=localhost; AttachDbFilename=E:\myDB\DB1.mdf; trusted_connection=yes

【问题讨论】:

标签: c# sql


【解决方案1】:

您要做的是将连接字符串添加到项目解决方案中的 App.ConfigWeb.config(取决于您的项目类型)文件中。它可能看起来像这样:

<?xml version="1.0"?>
<configuration>
  <connectionStrings>
    <add name="MyConnection" 
    connectionString="Data Source=localhost; AttachDbFilename=E:\myDB\DB1.mdf; trusted_connection=yes"/>
  </connectionStrings>
</configuration> 

接下来,您应该包含以下参考:

using System.Configuration;

现在你可以得到你的字符串如下:

string connectionString = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;

即使在您的代码中使用System.Configuration;,也可能找不到ConfigurationManager。要解决这个问题:

  1. Solution Explorer中右键单击References
  2. 点击添加参考
  3. 查找并添加System.Configuration.dll

【讨论】:

    【解决方案2】:

    您可以为所有数据操作使用一个连接,但更好的方法是从表单中删除所有数据操作,并将这些操作放在处理数据操作的类中。此外,如果每个方法连接共享连接字符串,我会建议与上述内容一起为每种方法使用一个连接。这是我为 MSDN 编写的代码示例的示例。请注意,每个方法连接都不是共享的,它是方法的本地连接,并且使用了 using 语句,该语句将在完成时关闭连接。对于简单的应用来说,重复使用一个连接是可以的,但一旦与一个有许多用户的更复杂的应用一起使用,请考虑节​​省资源并保持连接打开的时间只够用于预期的操作。

    概念示例。

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.SqlClient;
    
    namespace DataOperations_cs
    {
        public class BackendOperations
        {
            public string ConnectionString { get; set; }
            public DataTable DataTable { get; set; }
            public List<string> ContactTitles { get; set; }
            public Exception Exception { get; set; }
    
            public bool HasException
            {
                get
                {
                    return this.Exception != null;
                }
            }
    
            public bool RetrieveAllRecords()
            {
                this.DataTable = new DataTable();
                try
                {
                    using (SqlConnection cn = new SqlConnection { ConnectionString = this.ConnectionString })
                    {
                        using (SqlCommand cmd = new SqlCommand { Connection = cn, CommandType = CommandType.StoredProcedure, CommandText = "dbo.[SelectAllCustomers]" })
                        {
                            try
                            {
                                cn.Open();
                            }
                            catch (SqlException sqlex)
                            {
    
                                if (sqlex.Message.Contains("Could not open a connection"))
                                {
                                    this.Exception = sqlex;
                                    return false;
                                }
                            }
    
                            this.DataTable.Load(cmd.ExecuteReader());
                        }
                    }
    
                    if (ContactTitles == null)
                    {
                        RetrieveContactTitles();
                    }
    
                    this.Exception = null;
                    return true;
                }
                catch (Exception ex)
                {
                    this.Exception = ex;
                    return false;
                }
            }
    
            public bool RetrieveAllRecordsbyContactTitle(string contactType)
            {
                this.DataTable = new DataTable();
                try
                {
                    using (SqlConnection cn = new SqlConnection { ConnectionString = this.ConnectionString })
                    {
                        using (SqlCommand cmd = new SqlCommand { Connection = cn, CommandType = CommandType.StoredProcedure, CommandText = "dbo.ContactByType" })
                        {
                            cmd.Parameters.Add(new SqlParameter { ParameterName = "@ContactTitleType", SqlDbType = SqlDbType.NVarChar });
                            cmd.Parameters["@ContactTitleType"].Value = contactType;
                            cn.Open();
                            this.DataTable.Load(cmd.ExecuteReader());
                        }
                    }
    
                    this.Exception = null;
                    return true;
                }
                catch (Exception ex)
                {
                    this.Exception = ex;
                    return false;
                }
            }
    
            public bool RetrieveContactTitles()
            {
                if (ContactTitles != null)
                {
                    return true;
                }
    
                try
                {
                    using (SqlConnection cn = new SqlConnection { ConnectionString = this.ConnectionString })
                    {
                        using (SqlCommand cmd = new SqlCommand { Connection = cn, CommandType = CommandType.StoredProcedure, CommandText = "dbo.[SelectContactTitles]" })
                        {
                            cn.Open();
                            SqlDataReader reader = cmd.ExecuteReader();
                            if (reader.HasRows)
                            {
                                this.ContactTitles = new List<string>();
                                while (reader.Read())
                                {
                                    this.ContactTitles.Add(reader.GetString(0));
                                }
                            }
                        }
                    }
    
                    this.Exception = null;
                    return true;
                }
                catch (Exception ex)
                {
                    this.Exception = ex;
                    return false;
                }
            }
    
            public int AddCustomer(string CompanyName, string ContactName, string ContactTitle)
            {
                try
                {
                    using (SqlConnection cn = new SqlConnection { ConnectionString = this.ConnectionString })
                    {
                        using (SqlCommand cmd = new SqlCommand { Connection = cn, CommandType = CommandType.StoredProcedure, CommandText = "dbo.InsertCustomer" })
                        {
                            cmd.Parameters.Add(new SqlParameter { ParameterName = "@CompanyName", SqlDbType = SqlDbType.NVarChar });
                            cmd.Parameters.Add(new SqlParameter { ParameterName = "@ContactName", SqlDbType = SqlDbType.NVarChar });
                            cmd.Parameters.Add(new SqlParameter { ParameterName = "@ContactTitle", SqlDbType = SqlDbType.NVarChar });
                            cmd.Parameters.Add(new SqlParameter { ParameterName = "@Identity", SqlDbType = SqlDbType.Int, Direction = ParameterDirection.Output });
    
                            cmd.Parameters["@CompanyName"].Value = CompanyName;
                            cmd.Parameters["@ContactName"].Value = ContactName;
                            cmd.Parameters["@ContactTitle"].Value = ContactTitle;
                            cn.Open();
                            var affected = cmd.ExecuteScalar();
    
                            this.Exception = null;
                            return Convert.ToInt32(cmd.Parameters["@Identity"].Value);
                        }
                    }
                }
                catch (Exception ex)
                {
                    this.Exception = ex;
                    return -1;
                }
            }
    
            public bool RemoveCustomer(int Indentifier)
            {
                using (SqlConnection cn = new SqlConnection { ConnectionString = this.ConnectionString })
                {
                    using (SqlCommand cmd = new SqlCommand { Connection = cn, CommandType = CommandType.StoredProcedure, CommandText = "dbo.[DeleteCustomer]" })
                    {
                        cmd.Parameters.Add(new SqlParameter { ParameterName = "@Identity", SqlDbType = SqlDbType.Int });
                        cmd.Parameters.Add(new SqlParameter { ParameterName = "@flag", SqlDbType = SqlDbType.Bit, Direction = ParameterDirection.Output });
    
                        cmd.Parameters["@Identity"].Value = Indentifier;
                        cmd.Parameters["@flag"].Value = 0;
    
                        try
                        {
                            cn.Open();
                            var affected = cmd.ExecuteNonQuery();
                            this.Exception = null;
                            if (Convert.ToBoolean(cmd.Parameters["@flag"].Value))
                            {
                                return true;
                            }
                            else
                            {
                                return false;
                            }
                        }
                        catch (Exception ex)
                        {
                            this.Exception = ex;
                            return false;
                        }
                    }
                }
            }
    
            public bool UpdateCustomer(int PrimaryKey, string CompanyName, string ContactName, string ContactTitle)
            {
                try
                {
                    using (SqlConnection cn = new SqlConnection { ConnectionString = this.ConnectionString })
                    {
                        using (SqlCommand cmd = new SqlCommand { Connection = cn, CommandType = CommandType.StoredProcedure, CommandText = "dbo.[UpateCustomer]" })
                        {
                            cmd.Parameters.Add(new SqlParameter { ParameterName = "@CompanyName", SqlDbType = SqlDbType.NVarChar });
                            cmd.Parameters.Add(new SqlParameter { ParameterName = "@ContactName", SqlDbType = SqlDbType.NVarChar });
                            cmd.Parameters.Add(new SqlParameter { ParameterName = "@ContactTitle", SqlDbType = SqlDbType.NVarChar });
                            cmd.Parameters.Add(new SqlParameter { ParameterName = "@Identity", SqlDbType = SqlDbType.Int });
                            cmd.Parameters.Add(new SqlParameter { ParameterName = "@flag", SqlDbType = SqlDbType.Bit, Direction = ParameterDirection.Output });
    
                            cmd.Parameters["@CompanyName"].Value = CompanyName;
                            cmd.Parameters["@ContactName"].Value = ContactName;
                            cmd.Parameters["@ContactTitle"].Value = ContactTitle;
                            cmd.Parameters["@Identity"].Value = PrimaryKey;
                            cmd.Parameters["@flag"].Value = 0;
    
                            cn.Open();
                            var affected = cmd.ExecuteNonQuery();
                            this.Exception = null;
    
                            if (Convert.ToBoolean(cmd.Parameters["@flag"].Value))
                            {
                                return true;
                            }
                            else
                            {
                                return false;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    this.Exception = ex;
                    return false;
                }
            }
        }
    }
    

    【讨论】:

      【解决方案3】:

      是的,您可以通过将其存储在 web.config 文件或 app.config 文件中来使用它,以防 windows 窗体应用程序,然后重复使用它

      System.Configuration.ConfigurationManager.
      ConnectionStrings["connectionStringName"].ConnectionString;
      

      其中 connectionStringName 是存储在 web.config 文件中的连接字符串的名称

      【讨论】:

      【解决方案4】:

      这是最好的策略:

      在您的应用程序中使用 getConnection 方法创建一个静态类

      public class StaticContext
      {
          public static SqlConnection getConnessione()
          {
              string conn = string.Empty;
              conn = System.Configuration.ConfigurationManager.ConnectionStrings["connectionStringName"].ConnectionString;
              SqlConnection aConnection = new SqlConnection(conn);
              return aConnection;
          }
      }
      

      在每个表单中,当你需要连接时,使用这种方式:

      try
      {
          try
          {
              conn = StaticContext.getConnessione();
      
              SqlCommand aCommand = new SqlCommand("SELECT.....", conn);
      
              conn.Open();
              aReader = aCommand.ExecuteReader();
      
      
      
              while (aReader.Read())
              {
                  //TODO
              }
      
      
      
          }
          catch (Exception e)
          {
              Console.Write(e.Message);
          }
      }
      
      
      finally
      {
          conn.Close();
      }
      

      【讨论】:

        【解决方案5】:

        是的,你可以。虽然,您可能希望寻找不必一直重复代码的方法,这样如果连接字符串发生更改,您只需更改一次,而不是多次。一种方法是在配置文件中包含连接字符串。您可以拥有一个包含连接字符串的类的静态实例或一个简单的连接工厂。

        public static class ConnectionFactory{
            private static string connectionString = "connection string"; //You could get this from config file as other answers suggest.
        
            public static SqlConnection GetConnection(){
                 return new SqlConnection(connectionString);
            }
        }
        

        未经测试,因此可能存在一些语法错误。

        【讨论】:

          【解决方案6】:

          背后有一个相当智能的机制:Connection Pooling。连接保持可用一段时间。如果您再次需要连接并且传入完全相同的连接字符串(区分大小写),则将重复使用相同的连接。

          意思是:

          • 是的,您可以在应用程序中使用一个“全局”连接
          • 在大多数情况下不会产生影响 :-)

          【讨论】:

            【解决方案7】:

            是的,您绝对可以,最好的方法是在 web.configapp.config 中定义连接字符串,然后将它们读取到您的应用程序中

            System.Configuration.ConfigurationManager.ConnsectionStrings["CS"].ConnestionString
            
              <connectionStrings>
                <add name="CS" connectionString="Data Source=localhost; AttachDbFilename=E:\myDB\DB1.mdf; trusted_connection=yes" providerName="Sysem.Data.SqlClient"/>
              </connectionStrings>
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2014-08-03
              • 2019-05-03
              • 1970-01-01
              • 2020-01-14
              • 1970-01-01
              • 1970-01-01
              • 2012-07-11
              相关资源
              最近更新 更多