访问web.config中数据库连接字符串

ConfigurationManager 成员
提供对客户端应用程序配置文件的访问。无法继承此类。

private  DataSet RunQuery(SqlCommand sqlQuery)
    {
        
string  connectionString  =
            ConfigurationManager.ConnectionStrings
            [
" NorthwindConnectionString " ].ConnectionString;
        SqlConnection DBConnection 
=
            
new  SqlConnection(connectionString);
        SqlDataAdapter dbAdapter 
=   new  SqlDataAdapter();
        dbAdapter.SelectCommand 
=  sqlQuery;
        sqlQuery.Connection 
=  DBConnection;
        DataSet resultsDataSet 
=   new  DataSet();
        
try
        {
            dbAdapter.Fill(resultsDataSet);
        }
        
catch
        {
            labelStatus.Text 
=   " Unable to connect to SQL Server. " ;
        }
        
return  resultsDataSet;
    }

//  Get connectionStrings.
static   void  GetConnectionStrings()
{
    
//  Get the connectionStrings.
    ConnectionStringSettingsCollection connectionStrings  =
         ConfigurationManager.ConnectionStrings;

    
//  Get the collection enumerator.
    IEnumerator connectionStringsEnum  =
        connectionStrings.GetEnumerator();

    
//  Loop through the collection and 
    
//  display the connectionStrings key, value pairs.
     int  i  =   0 ;
    Console.WriteLine(
" Connection strings. " );
    
while  (connectionStringsEnum.MoveNext())
    {
        
string  name  =  connectionStrings[i].Name;
        Console.WriteLine(
" Name: {0} Value: {1} " ,
        name, connectionStrings[name]);
        i 
+=   1 ;
    }

}

你可能感兴趣的:(config)