2014-01-30 73 views
3

我一直在尋找這個問題的解決方案,唯一可能提供解決方案的是我唯一沒有的解決方案,試過,因爲它涉及到改變系統屬性。如果可以,我想避免這種情況。MySQL「與SQL Server建立連接時發生網絡相關或特定於實例的錯誤」

連接字符串是正確的,但它仍然不會連接。

第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 
+2

異常清楚地表明它認爲您正在使用(或嘗試連接到)SQL Server ... –

+0

您沒有使用MySql.Data包中的MySqlClient類。非常直接的博客解釋可以在這裏找到:http://www.codeproject.com/Tips/423233/How-to-Connect-to-MySQL-Using-Csharp – Durandal

+1

你能夠連接到服務器資源管理器?我會說試試。從那裏你可以複製和粘貼連接字符串,以確保它是正確的。 – Aaron

回答

5

SqlConnection是SqlServer的。要連接到MySql,您需要下載一些drivers並在您的項目中引用它,並使用MySqlConnection來代替。

看看這個question和這個CodeProject sample

0

正如@JW Lim和@Kirk Woll所建議的,該問題是由於使用System.Data.SqlClient引起的,該問題與一起使用,該問題與SQLServer一起使用。

對於這個項目,看到我保持本地,使用MySql.Data.MySqlClient是正確的方法來解決這個問題。

相關問題