【问题标题】:C# SQL connection string variable?C# SQL 连接字符串变量?
【发布时间】:2025-12-05 08:20:25
【问题描述】:

在 C# WinForms 中,如果我想在整个应用程序中访问我的 SQL 连接字符串变量,我应该把它放在哪里?

现在我正在将它复制粘贴到任何我使用它的地方。

//Sql connection string

SqlConnection con = new SqlConnection(@"Data Source=" + globalvariables.hosttxt + "," + globalvariables.porttxt + "\\SQLEXPRESS;Database=ha;Persist Security Info=false; UID='" + globalvariables.user + "' ; PWD='" + globalvariables.psw + "'");
SqlCommand command = con.CreateCommand();

【问题讨论】:

    标签: c# sql variables connection-string


    【解决方案1】:

    您可以简单地使用 app.config(或 web.config)。它有一个用于连接字符串的特殊部分。 See the MSDN-article about that. 然后你可以在代码中检索字符串,就像 use1515791 已经指出的那样,像这样:

    ConfigurationManager.ConnectionStrings["NameOfConnectionStringInConfig"].ConnectionString
    

    【讨论】:

      【解决方案2】:

      我宁愿不使用 app.config 文件,因为它不安全且不易于破解(每个连接信息都以纯文本格式存储在这里)。

      如果我没有使用我的任何 DLL,我将 SqlConnection 放在 Program.cs 中,并使用公共 getter 和禁用 setter。我在 Program.cs 中进行了所有初始化,所以它看起来像这样:

      static class Program
          {
              private static SqlConnection con;
              internal static SqlConnection Con
              {
                  get
                  {
                      return con = new SqlConnection(@"Data Source=" + globalvariables.hosttxt + "," + globalvariables.porttxt + "\\SQLEXPRESS;Database=ha;Persist Security Info=false; UID='" + globalvariables.user + "' ; PWD='" + globalvariables.psw + "'");
                  }
              }
      
              [STAThread]
              static void Main()
              {
                  Application.EnableVisualStyles();
                  Application.SetCompatibleTextRenderingDefault(false);
                  Application.Run(new Form1());
              }
          }
      

      现在可以从您的 Form1.cs 中访问它(例如):

      public partial class Form1 : Form
          {
              public Form1()
              {
                  InitializeComponent();
      
                  SqlCommand cmd = new SqlCommand();
                  cmd.Connection = Program.Con;
              }
          }
      

      我已经创建了一个 DLL 来轻松连接到 SQL,如果您有兴趣,请查看here

      【讨论】:

        【解决方案3】:

        这是一个相当笼统的问题 imo.. 取决于应用程序结构等。我倾向于使用具有此类属性的类“ApplicationContext”。不过,也许

        ConfigurationManager.ConnectionStrings["whatever"].ConnectionString
        

        我认为经常使用(添加对 System.Configuration 的引用)

        顺便说一句,如果你“到处”使用它,你不需要一个适配器类吗?

        编辑

        public class DataAcces
        {
            private string Connectionstr;
            public DataAcces()
            {
                this.Connectionstr = ConfigurationManager.ConnectionStrings["whatever"].ConnectionString;
            }
            public object ReturnSomething()
            {
                 using(SqlConnection con = new SqlConnection(this.Connectionstr))
                 {
                 //do stuff to db and return something
                 }
            }
         }
        

        然后在你需要的时候

        ....
        {
            var whatYouNeed = (new DataAcces()).ReturnSomething();
        }
        

        错字发生 :) 这是我能想到的最容易使用的,不是最好的。

        【讨论】:

        • 我有 3 个表单,它们都使用需要连接字符串的 sql 查询。
        • 当您说适配器类时,您的意思是创建一个全局连接字符串。就像我的一些字符串已经有“全局变量”?
        • 不,我的意思是负责所有数据访问的类。这样所有的 sql 都在该类中定义。
        • 但是如何在 void 中调用连接类?
        • 我知道我可以创建一个公共 void 并从另一个 void 调用 et,如下所示:sqlcount(sender, e);但我不认为这可以用作连接字符串变量。