【问题标题】:Can't Connect C# with SQL Server无法将 C# 与 SQL Server 连接
【发布时间】:2019-04-27 11:47:46
【问题描述】:

我正在尝试编写一个与我的 SQL Server 数据库交互的程序。我在 Mac 上的 Parallels 上使用 C# 编程,SQL Server 通过 Docker 运行。

但我就是无法连接。我每次尝试都会遇到同样的错误。

我已经尝试通过以下方式允许远程访问 SQL Server:

EXEC sp_configure 'remote access', 1 ;  
GO  
RECONFIGURE ;  
GO 

但这并不能解决我的问题。

这是我的 C# 代码:

主类

Database database;

public Form1()
{
    InitializeComponent();
    database = new Database("localhost\\MSSQLSERVER", "user1", "topsecret", "master"); // \
}

private void connect_button_Click(object sender, EventArgs e)
{
    database.Connect();
}

数据库类:

class Database
{
    SqlConnectionStringBuilder builder;
    SqlConnection connection;

    public Database(string source, string userid, string password, string initialcatalog){
        this.builder = new SqlConnectionStringBuilder();
        this.builder.DataSource = source;
        this.builder.UserID = userid;
        this.builder.Password = password;
        this.builder.InitialCatalog = initialcatalog;
    }

    public void Connect()
    {
        try 
        {
            // Connect to SQL
            Console.WriteLine("Connecting to SQL Server ... ");
            this.connection = new SqlConnection(this.builder.ConnectionString);
            connection.Open();
            Console.WriteLine("Connected");
        }
        catch(SqlException sqle)
        {
            Console.WriteLine(sqle.Message);
        }
    }
}

我总是收到这个错误:

连接到 SQL Server 时出现与网络相关或特定于实例的错误。服务器未找到或无法访问。验证实例名称是否正确以及 SQL Server 是否允许远程连接。 (提供者:SQL 网络接口,错误:25 - 连接字符串无效)

【问题讨论】:

  • 您必须按照不同的步骤才能获得访问权限。你有sql server 的账号吗?比如用户名和密码?
  • 是的,我以前也创建过这样的:使用密码 = 'topsecret'、default_database = master、check_expiration = off、check_policy = off 创建登录用户 1;去吧,我可以用这个用户登录
  • 但我之前也用我的 sa 帐户尝试过,但我仍然遇到同样的错误
  • 你的数据库是在同一台电脑上还是不同的?
  • 数据库在同一台电脑上运行

标签: c# sql-server docker parallels


【解决方案1】:

MSSQLSERVER 是您机器上未命名的默认实例的实例名称 - 您不得在连接字符串中使用它。

试试这行代码:

database = new Database("localhost", "user1", "topsecret", "master");

完全没有明确的实例名称 - 只为当前机器指定localhost(或(local),或.) - 这就是你所需要的!

【讨论】:

  • 您好,感谢您的快速回答,但它仍然无法正常工作...没关系,如果我使用 'localhost、'(local)' 或 '.'
【解决方案2】:

这是 Parallels 的问题,因为 Parallels 无法访问 localhost。所以我必须像这样在 Visual Studio 中定义 Parallels 的 IP:

database = new Database("10.211.55.2", "user1", "topsecret", "Time");

【讨论】:

    猜你喜欢
    • 2019-01-03
    • 1970-01-01
    • 1970-01-01
    • 2018-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-08
    • 2013-06-03
    相关资源
    最近更新 更多