【问题标题】:Can't connect to local database using C# Visual Studio无法使用 C# Visual Studio 连接到本地数据库
【发布时间】:2015-10-26 04:50:28
【问题描述】:

我是数据库新手,我一直在学习一些教程,但我一直在尝试使用我在 Visual Studio 中创建的精简版连接到我的数据库。

我正在尝试通过以下方式连接到数据库:

string connection = "Data Source=C:/Users/PLOW/Documents/Visual Studio 2012/Projects/File Name/File Name/Users.sdf";

// Making SQL connection
SqlConnection cn = new SqlConnection(connection);
cn.Open();

这样做我得到这个错误:

“在建立与 SQL Server 的连接时发生与网络相关或特定于实例的错误。未找到或无法访问服务器...”

我试过了:

string connection = @"Data Source=|DataDirectory|\Users.sdf";

我得到同样的错误。我现在不知道如何连接它。

这是我的连接字符串:

【问题讨论】:

标签: c# sql-server database visual-studio visual-studio-2012


【解决方案1】:

由于您使用的是精简版,所以这里不需要SqlConnection 对象,而是使用SqlCeConnection 并添加对System.Data.SqlServerCe 的引用。

使用SqlCeCommand 代替SqlCommand

【讨论】:

  • 测试了它并且有效。连接已建立。但是,通过了另一个错误: SqlCommand cmd = new SqlCommand(sqlAddUserPass, cn); sqlAddUserPass 是插入查询
  • 我正在尝试使用 SqlCommand 插入数据,但由于我更改了与 SqlCeConnection 的连接而出现过载错误。尽管如此,您回答了我最初的问题,所以我将其标记为已回答。
  • 使用SqlCeCommand而不是SqlCommand并告诉我它是否解决了:)
【解决方案2】:

如果是连接字符串的问题,你必须声明所需的参数来生成连接字符串

Data Source=servername;Initial Catalog=DbName;Integrated Security=True;User ID=userName;Password=password

【讨论】:

    猜你喜欢
    • 2017-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多