2011-05-09 37 views
0

我從配置文件傳入的連接字符串中收到了一些奇怪的行爲。我正在構建一個n層的網站(使用C#類庫和一個C#ASP.NET網站),並獲得了一個基本頁面,用於從數據庫(Microsoft SQL Server 2008)中提取一些數據,通過數據訪問和業務層,並將其顯示在網頁上。這在數據訪問層中使用硬編碼的連接字符串是成功的。來自web.config的連接字符串失敗,其中硬編碼字符串完全相同(使用C#的ASP.NET)

爲了改善體系結構,我將連接字符串移除到網站中的web.config文件。連接字符串已成功從web.config中檢索,但在使用此連接字符串調用.open()方法時連接失敗。

有了此構造,數據庫連接完美的作品:

public PathwayAccess() { 
    connectionString = "server=.\\MYSERVER;database=MyDatabase;Integrated Security=SSPI;"; 
} 

具有以下,字符串檢索,可以寫出調試和看起來不錯,並沒有拋出異常:

編輯的web.config

<?xml version="1.0"?> 
<configuration> 

    <system.web> 
     <compilation debug="false" targetFramework="4.0" /> 
     <customErrors mode="Off"/> 
    </system.web> 

    <connectionStrings> 
    <clear/> 
    <add name="MySqlClientConnectionString" 
    providerName="System.Data.SqlClient" 
    connectionString="server=.\\MYSERVER;database=MyDatabase;Integrated Security=SSPI;" /> 
    <!-- EDIT: problem was the escaped \ in the connection string: 
       should have been .\MYSERVER instead of .\\MYSERVER as 
       it doesn't need to be escaped in the config file --> 
    </connectionStrings> 

</configuration> 

和新構造我的數據訪問類:

public PathwayAccess() { 

    ConnectionStringSettingsCollection settings = ConfigurationManager.ConnectionStrings; 
    if (settings != null) { 
     foreach (ConnectionStringSettings cs in settings) { 
      if (cs.Name == "MySqlClientConnectionString" && cs.ProviderName == "System.Data.SqlClient") { 

       connectionString = cs.ConnectionString.ToString(); 
       return; 
      } 
     } 
     throw new Exception("The SqlClient connection string named 'MySqlClientConnectionString' was not found in connection.config. " 
      + "Found " + settings.Count + " connection strings"); 
    } else { 
     throw new Exception("Could not retrieve the connection string from a configuration file. Check the connection strings section of the relevant config file"); 
    } 
} 

但上面的第一個構造函數後,下面的代碼將工作,但之後的第二引發InvalidOperationException(有消息「實例失敗」):

myConnection = new SqlConnection(connectionString); 
myConnection.Open(); 

我這個很疑惑 - 由於某些原因,配置文件中的連接字符串看起來與硬編碼的連接字符串相同,但行爲不同。任何想法可能會發生什麼?

+1

請出示web.config中。 – 2011-05-09 08:58:11

+1

它們是否包含任何*雙斜槓*? – V4Vendetta 2011-05-09 09:16:39

+1

調試你的連接字符串。 btw:如果你只有一個cs,你可以使用它:connectionString = ConfigurationManager.ConnectionStrings [0] .ConnectionString或connectionString = ConfigurationManager.ConnectionStrings [「MySqlClientConnectionString」]。ConnectionString – ibram 2011-05-09 09:36:49

回答

相關問題