【问题标题】:Short hand for getting connection string from config file?从配置文件中获取连接字符串的简写?
【发布时间】:2011-02-03 16:37:58
【问题描述】:

我正在创建一个 SQL 连接,当我说到重点时:

SqlCommand cmd = new SqlCommand("test",

intellisense 提示我 connection:。我试着完成它:

SqlCommand cmd = new SqlCommand("test", connection:ConnStringName);

但这会出错。有没有一种简便的方法可以从我的配置文件中获取连接字符串?我似乎记得以前这样做过,但我认为它是在 .aspx 文件而不是 .cs 文件上。

【问题讨论】:

    标签: .net sql-server connection-string


    【解决方案1】:

    您看到的是 Visual Studio 为您提供了一个命名参数

    当您查看 SqlCommand 类时,它有几个构造函数 - 例如这个在这里:

    public SqlCommand(
        string cmdText,
        SqlConnection connection,
        SqlTransaction transaction
    )
    

    因此,使用 .NET 4 的命名参数,您可以想象调用此构造函数:

    SqlCommand cmd = new SqlCommand("...", connection:AValidSqlConnectionHere)
    

    但您必须为connection 参数提供SqlConnection 类型的值。这不是加载配置设置或其他东西的快捷方式 - 它只是命名参数的智能感知......

    目前,SqlCommand 类拥有一整套重载的构造函数,以应对提供更多或更少参数值的不同场景。使用 .NET 4.0 和 named and optional parameters,您可以只创建一个构造函数(或任何其他方法)并为某些参数提供默认值,并允许用户使用命名参数调用您的方法(或构造函数)以提供准确的信息他有空接听电话。

    【讨论】:

      【解决方案2】:

      使用 ConfigurationManager 类。

      ConfigurationManager.ConnectionStrings["YourConnectionStringName"];
      

      【讨论】:

        【解决方案3】:

        查看 ConfigurationManager 类,您可以从那里访问连接字符串

        【讨论】:

          【解决方案4】:

          你的意思是这样的:

          SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["nameofconnection"].ConnectionString
          SqlCommand cmd = new SqlCommand("test", con);
          

          【讨论】:

            猜你喜欢
            • 2013-04-15
            • 1970-01-01
            • 2012-01-26
            • 2020-05-01
            • 2015-06-02
            • 2020-03-17
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多