【问题标题】:how not to hard code connection stringin all pages如何不在所有页面中硬编码连接字符串
【发布时间】:2009-10-13 21:50:17
【问题描述】:

我有一个 webconfig 文件,其中有一个连接字符串...

但是当我访问数据库时,我必须一次又一次地编写相同的连接字符串...有没有办法可以从 webconfig 文件本身获取连接字符串的值..????

System.Data.SqlClient.SqlConnection dataConnection = new SqlConnection();
            dataConnection.ConnectionString =
                @"Data Source=JAGMIT-PC\SQLEXPRESS;Initial Catalog=SumooHAgentDB;Integrated Security=True";

            System.Data.SqlClient.SqlCommand dataCommand = new SqlCommand();
            dataCommand.Connection = dataConnection;

有什么建议吗??

【问题讨论】:

    标签: c# asp.net visual-studio-2008 sql-server-2005


    【解决方案1】:

    试试这个:

    string strConnString = 
    ConfigurationManager.ConnectionStrings["NameOfConnectionString"].ConnectionString;
    

    编辑: 您的代码现在看起来像这样:

    System.Data.SqlClient.SqlConnection dataConnection = new SqlConnection();
                dataConnection.ConnectionString =
                    ConfigurationManager.ConnectionStrings["NameOfConnectionString"].ConnectionString;
    
                System.Data.SqlClient.SqlCommand dataCommand = new SqlCommand();
                dataCommand.Connection = dataConnection;
    

    只需记住将 NameOfConnectionString 替换为连接字符串的实际名称,并添加对 System.Configuration 的引用(感谢 NissanFan!)

    【讨论】:

    • 确保在执行此操作之前添加对 System.Configuration 的引用。
    • 并确保将更新的(因为它未使用,可能已过时)连接字符串放在 /configuration/connectionStrings 配置单元中,在您的 web.config 中
    • 所以在这个即时硬编码数据源=JAGMIT-PC\SQLEXPRESS;Initial Catalog=SumooHAgentDB;Integrated Security=True 代替 NameofConnectionstring???
    • 那么我在代码中写的和你写的有什么区别...通过这样做我仍然在每个页面上写整个连接字符串,,,,
    • 不,webconfig 在 connectionstrings 部分中获取一行,将“NameOfConnectionString”与“Data Source=JAGMIT-PC\SQLEXPRESS;Initial Catalog=SumooHAgentDB;Integrated Security=True”相关联,这样您就不会到处都有硬编码的值。
    【解决方案2】:

    如何:从 Web.config 文件中读取连接字符串

    http://msdn.microsoft.com/en-us/library/ms178411.aspx

    【讨论】:

      【解决方案3】:

      在 .NET 中有一个名为 My.Settings 的标准对象,它会自动引用您在 webconfig 文件中的所有设置。

      您将那里的值称为My.Settings.Item("settingName")

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-24
        • 1970-01-01
        • 2016-06-04
        • 2014-09-22
        • 2015-10-07
        • 2017-09-29
        相关资源
        最近更新 更多