将SQL Server 2012数据库连接到Visual Studio 2012

时间:2017-10-01 03:57:44

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

我正在尝试使用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。我该如何解决这个问题?

3 个答案:

答案 0 :(得分:1)

您的连接字符串Integrated Security=True。这意味着将忽略您指定的User IdPassword属性,并将使用当前的Logged Windows Identity。

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

可在MSDN SqlConnection.ConnectionString Property

找到更多详情
  

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

答案 1 :(得分:0)

更改您的连接字符串,如下所示。因为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";

答案 2 :(得分:0)

你可以试试这个:

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

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