简体   繁体   中英

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";
                try
                {
                    conn.Open();
                    MessageBox.Show("Connection Established!");
                    conn.Close();
                }

                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 'System.Data.SqlClient.SqlException' 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.

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";
Console.WriteLine(builder.ConnectionString);

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.

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

Add a semicolon after each part of your connection string code:

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/ should tell you more about the correct format.

Your connectionstring is not well formated, you forgot some ; :

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

An example :

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

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

There are some ';' missing. Try this:

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

Use StringBuilder if you wants to write ConnectionString like mention,

String object it will occupy memory each time .

StringBuilder will occupy memory only once , so it will give you better performance .

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!");
}

Semi Column is missing in the Connection String. So correct it

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!");
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM