2016-08-19 42 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!"); 
      } 
     }