sql-server - SQL Server Compact - 连接到 SDF 数据文件

标签 sql-server

我正在 Visual Studio Express 2012 for web 中创建简单的 CRUD Web 应用程序(库)作为学校项目。我受到这个非常好的教程的启发 - http://www.asp.net/mvc/tutorials/mvc-music-store/mvc-music-store-part-1

现在我在连接 SQL Server Compact 版本 .sdf 数据文件时遇到问题。

web.config中我有这个连接字符串:

<connectionStrings>
    <add name="LibraryEntities"
     connectionString="Data Source=C:\Users\Administrator\Documents\Visual Studio 2012\Projects\2OBOP3_KU1\R10491\App_Data\R10491_library.sdf;"
     providerName="System.Data.SqlServerCe.4.0"/>
  </connectionStrings>

我创建了简单的 ASPX 文件用于数据库连接测试:

<script runat="server">
  protected void Page_Load(object sender, EventArgs e)
  {
      using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["LibraryEntities"].ToString()))
      {
          SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM Writers", cn);
          cn.Open();
          SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
          rdr.Read();
          Response.Write(rdr[0].ToString()); //read a value
      }
  }
</script>

当我运行应用程序时,它会抛出异常:

Exception Details: System.Data.SqlClient.SqlException: 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)

但是,当我尝试在“数据库资源管理器”菜单(“解决方案资源管理器”旁边)的“数据库资源管理器”选项卡中连接到我的 .sdf 文件时,我连接成功。

所以我假设连接字符串应该有问题 - 不是吗?谢谢您的建议。

最佳答案

您正在连接到 SQL Server Compact,而不是 SQL Server。

您应该使用SqlCeConnection而不是SqlConnection

  using System.Data.SqlServerCe;

  protected void Page_Load(object sender, EventArgs e)
  {
      using (SqlCeConnection cn = new SqlCeConnection(ConfigurationManager.ConnectionStrings["LibraryEntities"].ToString()))
      {
          SqlCeCommand cmd = new SqlCeCommand("SELECT COUNT(*) FROM Writers", cn);
          cn.Open();
          SqlCeDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
          rdr.Read();
          Response.Write(rdr[0].ToString()); //read a value
      }
  }

您还需要引用system.data.sqlserverce.dll

关于sql-server - SQL Server Compact - 连接到 SDF 数据文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14102245/

相关文章:

sql-server - 将表达式转换为数据类型数值时出现算术溢出错误

sql-server - Postgres OpenXML

sql - 根据列 2 和列 3 的排列查询 SQL Server 中的表

sql - 在 SQL 中将多行合并为一行

sql-server - 连接派生表时获取 “No column was specified for column 1"

python - sqlalchemy + pyodbc如何信任证书?

c# - 为什么重用 DataContext 会对性能产生负面影响?

c# - TransactionScope TransactionAborted 异常 - 事务未回滚。应该吗?

SQL Server : replace year of datetime with current year in Select

java - SqlConnection 在连接测试时抛出错误