2016-08-19 40 views
3

您好我是新來的,當涉及到連接到服務器/數據庫,並想知道爲什麼這會返回一個錯誤。C#SQL連接字符串返回錯誤

我有一個FastHost服務器與數據庫。

我剛剛舉了一個示例IP,但我一直在使用我的控制面板上給出的網站上。

private void SQLTest_Click(object sender, RoutedEventArgs e) 
      { 
       SqlConnection conn = new SqlConnection(); 
       conn.ConnectionString = 
        "Data Source = 123.456.789.012" + 
        "Initial Catalog = DiscoverThePlanet" + 
        "User ID = TestUser" + 
        "Password = Test"; 
       try 
       { 
        conn.Open(); 
        MessageBox.Show("Connection Established!"); 
        conn.Close(); 
       } 

       catch (Exception ex) 
       { 
        MessageBox.Show("Can not open Connection!"); 
       } 
      } 

這將返回

Can not open Connection!" message.

我得到以下顯示在我的代碼: 'System.Data.SqlClient.SqlException'類型的異常出現在system.data.dll但在用戶代碼中沒有處理

附加信息:建立到SQL Server的連接時發生網絡相關或特定於實例的錯誤。服務器未找到或無法訪問。驗證實例名稱是否正確,並將SQL Server配置爲允許遠程連接。 (提供程序:命名管道提供程序,錯誤:40 - 無法打開連接到SQL Server)

我知道我的服務器很好,因爲我已經連接到SQL Server Management Studio並添加了表和數據。

回答

7

你錯過了幾個;

conn.ConnectionString = 
        "Data Source = 123.456.789.012" + 
        ";Initial Catalog = DiscoverThePlanet" + 
        ";User ID = TestUser" + 
        ";Password = Test"; 

一個更好的解決方案是使用ConnectionStringBuilder

System.Data.SqlClient.SqlConnectionStringBuilder builder = 
    new System.Data.SqlClient.SqlConnectionStringBuilder(); 
builder["Data Source"] = "123.456.789.012"; 
builder["Initial Catalog"] = "DiscoverThePlanet"; 
builder["User ID"] = "TestUser"; 
builder["Password"] = "Test"; 
Console.WriteLine(builder.ConnectionString); 

或(如提到的@Fischermaen)您可以使用屬性而不是索引。它更具可讀性!

builder.DataSource = "123.456.789.012"; 
    builder.InitialCatalog = "DiscoverThePlanet"; 
    builder.UserID = "TestUser"; 
    builder.Password = "Test"; 

而且,在這種情況下,您不使用任何用戶輸入,但connection string injection提防手動創建您的連接字符串時。 ConnectionStringBuilder可以幫助你避免這些。

A connection string injection attack can occur when dynamic string concatenation is used to build connection strings that are based on user input. If the string is not validated and malicious text or characters not escaped, an attacker can potentially access sensitive data or other resources on the server. For example, an attacker could mount an attack by supplying a semicolon and appending an additional value. The connection string is parsed by using a "last one wins" algorithm, and the hostile input is substituted for a legitimate value.

The connection string builder classes are designed to eliminate guesswork and protect against syntax errors and security vulnerabilities. They provide methods and properties corresponding to the known key/value pairs permitted by each data provider. Each class maintains a fixed collection of synonyms and can translate from a synonym to the corresponding well-known key name. Checks are performed for valid key/value pairs and an invalid pair throws an exception. In addition, injected values are handled in a safe manner.

最後一個(和,在我看來,最好的)替代方案是move your connectionstring from code into a config。這將使您更容易在不同的環境中使用相同的代碼。

conn.ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString]; 

而你的配置。

<connectionStrings> 
    <add name="MyConnectionString" connectionString="[ConnectionString goes here]" providerName="System.Data.SqlClient" /> 
</connectionStrings> 
+0

輝煌,沒有意識到這是如此簡單。 –

+1

使用ConnectionStringBuilder是你提到的一個很好的觀點,但我更願意使用屬性而不是索引器!像'builder.DataSource =「123.456.789.012」' – Fischermaen

+0

@Fischermaen,很好的反饋。我更新了答案。 – smoksnes

2

添加一個分號連接字符串代碼各部分後:

private void SQLTest_Click(object sender, RoutedEventArgs e) 
     { 
      SqlConnection conn = new SqlConnection(); 
      conn.ConnectionString = 
       "Data Source = 123.456.789.012;" + 
       "Initial Catalog = DiscoverThePlanet;" + 
       "User ID = TestUser;" + 
       "Password = Test"; 
      try 
      { 
       conn.Open(); 
       MessageBox.Show("Connection Established!"); 
       conn.Close(); 
      } 

      catch (Exception ex) 
      { 
       MessageBox.Show("Can not open Connection!"); 
      } 
     } 

https://www.connectionstrings.com/sql-server/應該告訴你更多關於正確的格式。

2

您的ConnectionString沒有很好地格式化,你忘了一些;

"Data Source = 123.456.789.012;Initial Catalog = DiscoverThePlanet;User ID = TestUser;Password = Test" 

一個例子:

Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword; 

https://www.connectionstrings.com/sql-server/

1

有一些 ';'失蹤。試試這個:

conn.ConnectionString = 
        "Data Source = 123.456.789.012;" + 
        "Initial Catalog = DiscoverThePlanet;" + 
        "User ID = TestUser;" + 
        "Password = Test;"; 
0

使用StringBuilder的如果你想要寫的ConnectionString像提,

String對象它將佔用內存每次

StringBuilder將只佔用一次內存,所以它會給你更好的性能

SqlConnection conn = new SqlConnection(); 
StringBuilder sb=new StringBuilder(); 
sb.Append("Data Source = 123.456.789.012;"); 
sb.Append("Initial Catalog = DiscoverThePlanet;"); 
sb.Append("User ID = TestUser;"); 
sb.Append("Password = Test;"); 
conn.ConnectionString =sb.ToString(); 
try 
{ 
    conn.Open(); 
    MessageBox.Show("Connection Established!"); 
    conn.Close(); 
} 

catch (Exception ex) 
{ 
    MessageBox.Show("Can not open Connection!"); 
} 
+0

用StringBuilder建立一個連接字符串在我看來像是用大錘打破螺母;-)不要誤解我的意思,StringBuilder對於大數的字符串操作,但是爲了構建連接字符串,它看起來有點過於工程化。 – Fischermaen

+0

是的你是對的,如果它要執行一次不是問題,我建議,所以OP可以使用String-builder在未來的其他地方連接字符串。 –

0

連接字符串中缺少半列。所以糾正它

private void SQLTest_Click(object sender, RoutedEventArgs e) 
     { 
      SqlConnection conn = new SqlConnection(); 
      conn.ConnectionString = 
       "Data Source = 123.456.789.012;" + 
       "Initial Catalog = DiscoverThePlanet;" + 
       "User ID = TestUser;" + 
       "Password = Test;"; 
      try 
      { 
       conn.Open(); 
       MessageBox.Show("Connection Established!"); 
       conn.Close(); 
      } 

      catch (Exception ex) 
      { 
       MessageBox.Show("Can not open Connection!"); 
      } 
     }