MySQL“建立与 SQL Server 的连接时发生网络相关或特定于实例的错误”

Posted

技术标签:

【中文标题】MySQL“建立与 SQL Server 的连接时发生网络相关或特定于实例的错误”【英文标题】:MySQL "network-related or instance-specific error occurred while establishing a connection to SQL Server" 【发布时间】:2014-02-22 04:09:04 【问题描述】:

我一直在寻找解决此问题的方法,唯一可能提供解决方案的方法是我唯一没有尝试过的方法,因为它涉及更改系统属性。如果可以的话,我想避免这种情况。

连接字符串正确,但仍无法连接。

异常发生在第 30 行,即打开连接字符串的位置。 conn.Open()

代码如下:

using System.Text;
using System.Data.SqlClient;

namespace My_Sql_Program

    class Program
    
        static void Main()
        
            try
            
                // Step 1: Create a SqlConnection Object to connect to the 
                // SQL Northwind database.
                SqlConnection conn = new SqlConnection("server=localhost;database=dcim;uid=root;pwd=LlmD62jL");

                // Step 2: Create a SqlCommand object.
                SqlCommand cmd = conn.CreateCommand();

                // Step 3: Set the CommandText property of the SqlCommand object to a 
                // SQL SELECT statment that retrieves a row from the Customers table.
                cmd.CommandText = "SELECT UserName, UserPassword, AuthorityLevel, " +
                    "FROM Users " +
                    "WHERE UserName = 'ben'";

                // Step 4: Open the database connection using the 
                // Open() method of the SqlConnection object.
                conn.Open();

                //Step 5: Create a SqlDataReader object and call the ExecuteReader()
                //Method of the SqlCommand object to run the SELECT statement.
                SqlDataReader rdr = cmd.ExecuteReader();

                // Step 6: Read the row from the SqlDataReader object using the Read() method.
                rdr.Read();

                // Step 7: Display the column values.
                Console.WriteLine("rdr[\"UserName\"] = " + rdr["UserName"]);
                Console.WriteLine("rdr[\"UserPassword\"] = " + rdr["UserPassword"]);
                Console.WriteLine("rdr[\"AuthorityLevel\"] = " + rdr["AuthorityLevel"]);

                // Step 8: Close the SqlReader object using the Close() method.
                rdr.Close();

                // Step9: Close the SqlConnection object using the Close() method.
                conn.Close();
            
            catch (SqlException e) 
            
                Console.WriteLine("An SqlException was thrown.");
                Console.WriteLine("Number = " + e.Number);
                Console.WriteLine("Message = " + e.Message);
                Console.WriteLine("StackTrace:\n" + e.StackTrace);
            
            Console.ReadLine();
        
    

当我运行它时,大约 30 秒内没有任何反应,然后打印 SqlException

An SqlException was thrown.
Number = 2
Message = 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: Named Pipes
Provider, error: 40 - Could not open a connection to SQL Server)

StackTrace:
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean
breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean
breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj,
Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds
connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean
trustServerCert, Boolean integratedSecurity, Boolean withFailover)
   at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String
newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout,
Boolean withFailover)
   at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String
newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString
connectionOptions, SqlCredential credential, TimeoutTimer timeout)
   at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout,
SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString
newSecurePassword, Boolean redirectedUserInstance)
   at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity,
SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String
newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString
userConnectionOptions)
   at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options,
DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection
owningConnection, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool,
DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32
waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection,
DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject,
TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection,
TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection,
DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions
userOptions)
   at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.Open()
   at My_Sql_Program.Program.Main() in c:\users\paul\documents\visual studio 2010\Projects\My Sql
Program\My Sql Program\Program.cs:line 30

【问题讨论】:

异常清楚地表明它认为你正在使用(或试图连接)SQL Server... 您没有使用来自 mysql.Data 包的 MySqlClient 类。可以在这里找到非常直接的博客解释:codeproject.com/Tips/423233/… 你能连接到服务器资源管理器吗?我会说试试看。从那里您可以复制并粘贴连接字符串以确保它是正确的。 【参考方案1】:

SqlConnection 用于 SqlServer。要连接到 MySql,您需要下载一些 drivers 并在您的项目中引用它,并改用 MySqlConnection

看看这个question和这个CodeProject sample。

【讨论】:

【参考方案2】:

正如@JW Lim 和@Kirk Woll 所建议的,该问题是由与SQLServer 一起使用的System.Data.SqlClient 引起的。

对于这个项目,鉴于我将其保留为 本地,使用 MySql.Data.MySqlClient 是解决此问题的正确方法。

【讨论】:

以上是关于MySQL“建立与 SQL Server 的连接时发生网络相关或特定于实例的错误”的主要内容,如果未能解决你的问题,请参考以下文章

PHP sqlsrv_connect 到 SQL Server:建立与 SQL Server 的连接时发生与网络相关或特定于实例的错误

为啥在建立与 SQL Server 的连接时会发生与网络相关或特定于实例的错误?

疑难解答'建立与SQL Server的连接时发生的与网络相关或特定于实例的错误'连接到Azure SQL Server

管道错误40建立与SQL Server的连接时发生与网络相关或特定于实例的错误

Unable to connect to localDB in VS2012 – “建立与 SQL Server 的连接时发生网络相关或特定于实例的错误...”

MySQL