2015-12-08 69 views
0

我正在創建一個簡單的Windows C#表單應用程序。但我無法連接到本地數據庫文件(。自衛隊)如何連接到本地sdf文件?

我使用

using System.Data.SqlServerCe; 

這是我的app.config文件

<add name="ConnectionString1" 
     connectionString="Data Source=D:\Work Place_VS\Dilshan_Hardware\Dilshan_Hardware\Database\AppDB.sdf" 
     providerName="Microsoft.SqlServerCe.Client.3.5" /> 

<add name="ConnectionString2" 
     connectionString="Data Source=|DataDirectory|\Database\AppDB.sdf" 
     providerName="Microsoft.SqlServerCe.Client.3.5" /> 

我試圖連接數據庫通過下面的代碼文件。

try 
    { 
     using (SqlCeConnection cn = new SqlCeConnection(ConfigurationManager.ConnectionStrings["ConnectionString1"].ToString())) 
    { 
    SqlCeCommand cmd = new SqlCeCommand("SELECT routeName FROM tbl_route", cn); 
    cn.Open(); 
    SqlCeDataReader reader1 = cmd.ExecuteReader(); 

    while (reader1.Read()) 
    { 
     MessageBox.Show("Result :" + reader1[0]); 
    } 
    } 

} 
catch (Exception ex) 
{ 
    MessageBox.Show("Error :" + ex.ToString()); 

} 

即使我用ConnectionString1ConnectionString2它總是跳進catch塊,同時設法使的connectionString。

請幫我找到這段代碼的錯誤。

+0

什麼是異常消息? – DaniDev

回答

0

我認爲你需要添加一個Persist Security信息值

嘗試以下操作:

<add name="ConnectionString1" 
      connectionString="Data Source=D:\Work Place_VS\Dilshan_Hardware\Dilshan_Hardware\Database\AppDB.sdf;Persist Security Info=false;" 
      providerName="Microsoft.SqlServerCe.Client.3.5"