[英]Exception when attempting to connect to SQL Server CE from C#
I'm an newbie who is trying to get learn some web programming. 我是一个新手,正在尝试学习一些Web编程。 I'm making my site in VS 2012 using C#.
我正在使用C#在VS 2012中创建网站。 I've got a database connected in the App_Data folder, using SQL Server CE 4.0.
我已经使用SQL Server CE 4.0在App_Data文件夹中连接了一个数据库。 I'm attempting to connect to it as follows:
我尝试按以下方式连接到它:
SqlCeCommand cmd1 = new SqlCeCommand("SELECT Admin FROM SystemUsers WHERE Email=" + user.Email);
SqlCeDataReader admin = null;
SqlCeConnection conn = new SqlCeConnection();
conn.ConnectionString = "Data Source=MyData.sdf;Persist Security Info=False;";
conn.Open();
admin = cmd1.ExecuteReader();
When I execute this, I get the following error: 执行此操作时,出现以下错误:
An exception of type 'System.Data.SqlServerCe.SqlCeException' occurred in System.Data.SqlServerCe.dll but was not handled in user code
System.Data.SqlServerCe.dll中发生类型为'System.Data.SqlServerCe.SqlCeException'的异常,但未在用户代码中处理
Any thoughts as to what I'm doing wrong? 关于我在做什么错有什么想法吗? I've been trying to figure this out for hours.
我已经尝试了好几个小时了。
You said that your database is in the APP_Data directory, but your connection string assumes that is in the root directory of your site. 您说过数据库位于APP_Data目录中,但是您的连接字符串假定该数据库位于站点的根目录中。
Try with 试试看
conn.ConnectionString = @"Data Source|DataDirectory|\MyData.sdf;Persist Security Info=False;";
The |DataDirectory| | DataDirectory | is a placeholder string that the NET Framework changes to a predefined location where you data files are supposed to stay
是一个占位符字符串,NET Framework会更改为数据文件应保留在的预定义位置
And this is how I would change your code 这就是我要更改您的代码的方式
using(SqlCeConnection conn = new SqlCeConnection(@"Data Source|DataDirectory|\MyData.sdf;Persist Security Info=False;"))
using(SqlCeCommand cmd1 = new SqlCeCommand("SELECT Admin FROM SystemUsers WHERE Email=@mail", conn))
{
conn.Open();
cmd1.Parameters.AddWithValue("@mail", user.Email);
SqlCeDataReader admin = cmd1.ExecuteReader();
while(admin.Read())
{
.....
}
}
As you can see, I have made this changes: 如您所见,我进行了以下更改:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.