如何不在所有页面中硬编码连接字符串

use*_*084 0 c# asp.net sql-server-2005 visual-studio-2008

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

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

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;
Run Code Online (Sandbox Code Playgroud)

有什么建议??

Mat*_*nes 6

试试这个:

string strConnString = 
ConfigurationManager.ConnectionStrings["NameOfConnectionString"].ConnectionString;
Run Code Online (Sandbox Code Playgroud)

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

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

            System.Data.SqlClient.SqlCommand dataCommand = new SqlCommand();
            dataCommand.Connection = dataConnection;
Run Code Online (Sandbox Code Playgroud)

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