如何从 .NET 应用程序连接到 SQL Server Compact?
我想创建一个使用本地数据库的 WPF 应用程序。我创建了一个简单的数据库并添加了它,这样我就可以在解决方案资源管理器中看到我的数据库 NameDB.sdf
。
如何从我的应用程序连接到它?
我尝试过使用一个仅尝试连接到数据库的空应用程序:
...
using System.Data.SqlServerCe;
using System.Data;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
SqlCeConnection connection =
new SqlCeConnection(@"Data Source=|DataDirectory|\NameDB.sdf");
SqlCeCommand command = new SqlCeCommand("SELECT * FROM Names");
SqlCeDataAdapter dataAdapter = new SqlCeDataAdapter(command);
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
Console.WriteLine("Done");
}
}
但我收到 XamlParseException
并显示以下消息:
“对与指定绑定约束匹配的类型“WpfDBApp.MainWindow”上的构造函数的调用引发了异常。”行号“3”和行位置“9”。
我的连接字符串是 @"Data Source=|DataDirectory|\NameDB.sdf"
,因为我想使用“本地”路径而不是完整路径。这是取自我在下面链接的教程。
如何创建一个连接到本地数据库的简单应用程序?
我尝试遵循使用 SqlCeResultSet 和 Visual C#.NET 进行 SQL Server 2005 Compact Edition 数据访问 但似乎与 Visual Studio 2010 和 WPF。
I would like to create a WPF application that is using a local database. I have created a simple database and added it so I can see my database NameDB.sdf
in my Solution Explorer.
How do I connect to it from my application?
I have tried with an empty application that just tries to connect to the database:
...
using System.Data.SqlServerCe;
using System.Data;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
SqlCeConnection connection =
new SqlCeConnection(@"Data Source=|DataDirectory|\NameDB.sdf");
SqlCeCommand command = new SqlCeCommand("SELECT * FROM Names");
SqlCeDataAdapter dataAdapter = new SqlCeDataAdapter(command);
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
Console.WriteLine("Done");
}
}
But I get XamlParseException
with this message:
'The invocation of the constructor on type 'WpfDBApp.MainWindow' that matches the specified binding constraints threw an exception.' Line number '3' and line position '9'.
My connection string is @"Data Source=|DataDirectory|\NameDB.sdf"
, since I want to use a "local" path and not a full path. This is taken from the tutorial I link to below.
How can I create a simple application that connects to the local database?
I have tried to follow SQL Server 2005 Compact Edition Data Access with the SqlCeResultSet and Visual C#.NET but it doesn't seem to be done the same way with Visual Studio 2010 and WPF.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您没有初始化您的连接。
现在就试试吧。
You did not initialized your connection.
Try now.
问题是你的连接字符串。格式应为“Data Source="{FullPath to YourDatabase.sdf}"
请参阅 此 MSDN 示例 了解更多详细信息
The problem is your connection string. The format should be "Data Source="{FullPath to YourDatabase.sdf}"
See this MSDN example for more details