如何连接到本地sdf文件

本文关键字:sdf 文件 何连接 连接 | 更新日期: 2023-09-27 18:26:13

我正在创建一个简单的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,它也总是在尝试创建connectionString时跳到catch块中。

请帮我找出这个代码的错误。

如何连接到本地sdf文件

我认为您需要添加一个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"