簡體   English   中英

嘗試連接到.sdf數據庫時出現異常

[英]Exception when trying to connect to .sdf database

我在文件C:\\Users\\Pawel\\Documents\\DB.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

考慮使用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);

顯然,您使用的是SQL Compact Edition(sdf文件)。 您是否嘗試過使用SqlCeConnection而不是SqlConnection

作為獎勵:如果你不想再亂用連接線,請試試這個

這樣做,您必須添加對System.Data.SqlServerCe程序集的引用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM