2011-05-10 134 views
5

我有文件C:\Users\Pawel\Documents\DB.sdf中的数据库。我如何连接到它?尝试连接到.sdf数据库时出现异常

下面的简单代码不起作用并生成异常。

代码:

[WebMethod] 
public String TestCon() 
{ 
    SqlConnection sql = new System.Data.SqlClient.SqlConnection(
     @"Data Source=C:\Users\Pawel\Documents\DB.sdf"); 

    string str = "OK"; 

    try 
    { 
     sql.Open(); 
     sql.Close(); 
    } 
    catch (Exception ex) 
    { 
     str = ex.Message; 
    } 

    return str; 
} 

结果:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

我缺少什么?我应该怎么做才能正确打开连接?

编辑:
System.NotSupportedException: SQL Server Compact is not intended for ASP.NET development.
大:P

+0

您使用的是SqlCompact吗?在我看来你正在使用正常的SQL客户端 – 2011-05-10 18:04:09

回答

8

考虑使用System.Data.SqlServerCe.SqlCeConnection

System.Data.SqlServerCe.SqlCeConnection con = 
    new System.Data.SqlServerCe.SqlCeConnection(@"Data Source=C:\Users\Pawel\Documents\DB.sdf"); 

(添加到System.Data.SqlServerCe的引用,如果需要的话)

此外,为了在ASP.NET中使用它,请添加:

AppDomain.CurrentDomain.SetData("SQLServerCompactEditionUnderWebHosting", true); 
+0

命名空间'System.Data'中不存在类型或名称空间名称'SqlServerCe'(你缺少程序集引用吗?) – Ichibann 2011-05-10 18:07:05

+1

是的,你必须添加对系统的引用.Data.SqlServerCe程序集。 – Larry 2011-05-10 18:14:27

+0

您应该将对System.Data.SqlServerCe的引用添加到您的项目中。 (在解决方案资源管理器中右键点击'参考','添加参考',其余部分很容易) – Dmitry 2011-05-10 18:15:33

1

显然,您正在使用SQL Compact Edition(sdf文件)。您是否尝试过使用SqlCeConnection而不是SqlConnection

作为一个奖励:如果你不想再混淆connectionstrings,请尝试this

这样做,您必须添加对System.Data.SqlServerCe装配的参考。

相关问题