2013-07-22 27 views
0
DataSet ds = new DataSet("Transactions"); 

using (SqlConnection conn = new SqlConnection("myConnectionString")) 
{ 
    SqlCommand sqlComm = new SqlCommand("[dbo].[GetFullTransactionList]", conn); 
    sqlComm.CommandType = CommandType.StoredProcedure; 

    SqlDataAdapter da = new SqlDataAdapter(); 
    da.SelectCommand = sqlComm; 
    da.Fill(ds); 
} 

return ds; 

app.config相關內容:不能與連接字符串連接到數據庫中的app.config

<configuration> 
    <connectionStrings> 
     <add name="myConnectionString" 
      connectionString="Data Source=LAPTOP-LT;Initial Catalog=myDb;User ID=sa;Password=abc" 
      providerName="System.Data.SqlClient" /> 
    </connectionStrings> 
</configuration> 

我得到這個異常:

Format of the initialization string does not conform to specification starting at index 0. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: Format of the initialization string does not conform to specification starting at index 0.

源錯誤:

Line 44:    DataSet ds = new DataSet("Transactions"); 
Line 45:    using (SqlConnection conn = new SqlConnection("myConnectionString")) 
+0

是[DBO] [ GetFullTransactionList]存儲過程需要傳遞任何參數? –

回答

0

要使用連接str從配置文件中,您需要訪問它ConfigurationManager

因此,這將是:

using (SqlConnection conn = new 
    SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"])) 
    { 
      ... 
    } 

參考documentation以獲得更多信息

0

的SqlConnection期待一個真正的連接字符串不是從app.config中的關鍵。試着用

ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString 
1

正確的方式來閱讀它在App.config指連接字符串是:

string cnnString = ConfigurationManager.ConnectionStrings["yourCnnString"].ConnectionString; 
using(SqlConnection conn = new SqlConnection(cnnString)) 
{ 

} 

不要忘了最終財產ConnectionString

+0

它無法從App.config中訪問連接字符串 – vini

+0

你是什麼意思?你有什麼樣的錯誤信息?你包括'使用System.Configuration;'? – Steve

+0

它給出一個空引用異常。是的,我已經包括使用System.configuration; – vini