Luke Litherland Luke Litherland - 1 year ago 135
SQL Question

C# SQL Connection String returning error

Hi I'm new when it comes to connecting to a server/database and was wondering why this returns an error.

I have a FastHost server with a database.

I've just put in an example IP but i have been using the one given on my control panel on the site.

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";
MessageBox.Show("Connection Established!");

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

This returns the

Can not open Connection!" message.

I get the following show in my code:
An exception of type
occurred in System.Data.dll but was not handled in user code

Additional information: 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)

I know my server is fine because i have connected to it on SQL Server Management studio and added tables and data.

Answer Source

You're missing a couple of ;

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

An even better solution is to use 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";

Or (as @Fischermaen mentioned) you can use the properties, instead of indexes. It's even more readable!

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

Also, in this scenario you aren't using any user input, but beware of connection string injection when manually creating your connection string. ConnectionStringBuilder can help you avoid those.

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.

A last (and, in my opinion, best) alternative is to move your connectionstring from code into a config. This will make it much easier for you to use the same code in different environments.

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

And your config.

    <add name="MyConnectionString" connectionString="[ConnectionString goes here]" providerName="System.Data.SqlClient" />
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download