c# – SQL Server Compact Edition 4.0:错误:26 – 找到指定的服务器/实例时出错

我一直在开发一个控制台应用程序(C#/ .Net Framework 4.0 / VS2012).我创建了一个SQL Server Compact数据库(* .sdf)并添加了一个连接字符串:connectionStringsadd name=Dispatcher.Properties.Settings.FakeDat...

我一直在开发一个控制台应用程序(C#/ .Net Framework 4.0 / VS2012).我创建了一个SQL Server Compact数据库(* .sdf)并添加了一个连接字符串:

<connectionStrings>
    <add name="Dispatcher.Properties.Settings.FakeDataSetConnectionString"
        connectionString="Data Source=|DataDirectory|\FakeDataSet.sdf"
        providerName="Microsoft.SqlServerCe.Client.4.0" />
</connectionStrings>

但是当我尝试执行以下代码时:

SqlConnection con = new SqlConnection();
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Dispatcher.Properties.Settings.FakeDataSetConnectionString"].ToString();
con.Open();

它在con.Open()中给出以下异常:

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)

>我在这里做错了什么?
> SQL Server代理和SQL Server Browser都处于“已启动”状态.使用SQL Server Compact Edition时实际上是否重要?

解决方法:

对于SQL Server Compact,您需要使用SqlCeConnection(而不是SqlConnection – 这是“真正的”SQL Server版本).

SqlCeConnection con = new SqlCeConnection();
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Dispatcher.Properties.Settings.FakeDataSetConnectionString"].ToString();
con.Open();

当然,你还需要使用SqlCeCommand(而不是SqlCommand)等等……

有关System.Data.SqlServerCe命名空间中所有类的更多详细信息,请参阅MSDN SQL Server Books Online documentation

本文标题为:c# – SQL Server Compact Edition 4.0:错误:26 – 找到指定的服务器/实例时出错

基础教程推荐