【问题标题】:Connecting SQL Server 2012 database to Visual Studio 2012将 SQL Server 2012 数据库连接到 Visual Studio 2012
【发布时间】:2017-10-01 03:57:43
【问题描述】:

我正在尝试使用 SQL Server 2012 将我在 Visual Studio 中的项目连接到我的数据库。这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace CollegeManagementSystem.lib
{
public class DatabaseConnection
{
    public static SqlConnection Con;

    public static SqlConnection GlobalConnection()
    {
        string ConString = @"Data Source=DESKTOP-JTVC4I1\\SQLEXPRESS;" + Global.ServerName + ";Initial Catalog=College" + Global.Database + ";Integrated Security=True;User Id=sa" + Global.SUserId + ";Password=123" + Global.SPassword + ";Connection Timeout=1000";
        Con = new SqlConnection();
        Con.ConnectionString = ConString;
        if (Con.State == ConnectionState.Open)
        {
            Con.Close();
        }
        Con.Open();
        return Con;
    }

我的数据库的名称是college.db,我也很困惑,我在服务器中有一个名为master.db 的数据库,它具有我在数据库college.db 中创建的相同表,但我没有创建它。

我得到了错误:

发生网络相关或特定于实例的错误 建立与 SQL Server 的连接。找不到服务器或 无法访问。验证实例名称是否正确,并且 SQL Server 配置为允许远程连接。

我在本地运行我的 SQL Server。我该如何解决这个问题?

【问题讨论】:

  • Global.ServerName 的值是多少?
  • 公共静态字符串 ServerName = "DESKTOP-JTVC4I1\\SQLEXPRESS";
  • 设置断点,看看ConnString的值是多少。我怀疑你会看到问题所在。

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


【解决方案1】:

您的连接字符串是Integrated Security=True。这意味着您指定的 User IdPassword 属性将被忽略,并且将使用当前记录的 Windows 标识。

尝试将连接字符串更改为Integrated Security=False

更多详情请关注MSDN SqlConnection.ConnectionString Property

如果为 false,则在连接中指定用户 ID 和密码。如果为 true,则使用当前 Windows 帐户凭据进行身份验证。 识别值为true、false、yes、no、sspi(强烈推荐),相当于true。 如果指定了用户 ID 和密码并且集成安全设置为 true,则用户 ID 和密码将被忽略并使用集成安全。

【讨论】:

    【解决方案2】:

    你可以试试这个:

    string ConString = "Server=DESKTOP-JTVC4I1\\SQLEXPRESS;Database=College;User Id=sa;Password=123;"
    

    还要确保您的数据库名称正确。在描述中您说您的数据库名称是“college”,但在连接字符串中您使用了“College”。

    【讨论】:

      【解决方案3】:

      如下所示更改您的连接字符串。因为Global.ServerName 已经有服务器名称,但在您的代码中这会重复。另外我认为Global.DatabaseGlobal.SUserIdGlobal.SPassword 是重复的。

      string ConString = @"Data Source=" + Global.ServerName + 
              ";Initial Catalog=" + Global.Database + 
              ";Integrated Security=False;User Id=" + Global.SUserId + 
              ";Password=" + Global.SPassword + ";Connection Timeout=1000";
      

      【讨论】:

      • 数据库工作正常。但是当我尝试登录时提示用户名和密码不正确,用户名和密码都称为admin。
      • 你试过我更新的答案了吗?什么是实际的用户名密码? Global.SUserIdGlobal.SPassword 的值是多少。两者都一样吗?
      • 是的,我试过你的解决方案,Global.SUserId 和 Global.SPassword 的值也是 admin
      • SQL server中用户名密码的实际值是多少?
      • 删除Integrated Security=True
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-03
      • 1970-01-01
      • 2012-06-14
      相关资源
      最近更新 更多