2011-05-10 109 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裝配的參考。

相關問題