How to connect to local sdf file?

时间:2015-12-08 19:25:53

标签: c# sql database-connection sqlcedatareader

I'm creating a simple windows C# form application. but I cannot connect to local database file (.sdf)

i'm using

$ echo ""|perl -ne 'chomp;print 0+split/x/,$_,-1'
0

$ echo "x"|perl -ne 'chomp;print 0+split/x/,$_,-1'
2

$ echo "xx"|perl -ne 'chomp;print 0+split/x/,$_,-1'
3

$ echo "xxx"|perl -ne 'chomp;print 0+split/x/,$_,-1'
4

This is my app.config file

using System.Data.SqlServerCe;

I am trying to connect database file through following code.

<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" />

Even I use 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()); } or ConnectionString1 it always jump into catch block while try to make connectionString.

Please help me to find the error of this code.

1 个答案:

答案 0 :(得分: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"