1

I am creating an app with C++ language in .NET Framework I am trying to connect with SQL Server but I can't connect with it. The error massage is

[System.Data.SqlClient.SqlException: '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)']

My code for this app is

    #pragma endregion
    private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
        try
        {
            String^ connectionstring = "Data Source=localhost\sqlexpress;Initial Catalog=root_info;Integrated Security=True;";
            SqlConnection con(connectionstring);
            con.Open();
            String^ sqlquery = "insert into root_table values('"+this->textBox1+"','"+this->textBox2 +"')";
            SqlCommand cmd(sqlquery, % con);
            cmd.ExecuteNonQuery();
            con.Close();
            MessageBox::Show("datasubmited successfully", "success", MessageBoxButtons::OK);


        }
        catch (Exception^ ex)
        {
            throw ex;
        }
    }
    };
}
5
  • I've changed one of your tags to C++/CLI, because System::Object^ sender is not a valid C++. Commented May 7, 2024 at 8:04
  • And I changed another than, because the problem is related to the MS SQL Server product, not to the SQL language. Commented May 7, 2024 at 9:25
  • can you connect to the same instance: "localhost\sqlexpress" with SSMS? Commented May 7, 2024 at 9:41
  • 2
    What do you think \s means in your connection string? Escape symbols correctly! Commented May 7, 2024 at 9:47
  • 1
    There is also dangerous SQL injection going here, as well as that unnecessary throw ex will wipe the stack trace. Commented May 7, 2024 at 10:48

1 Answer 1

1

Maybe the problem is not so much in your C++ code, but in the connectivity of your SQL Express instance.

Have you tried connecting to this instance (from the same machine) using SQL Server Management Studio? If it fails as well, at least you can exclude your code from the troubleshooting.

Sign up to request clarification or add additional context in comments.

3 Comments

You should post this answer as a comment.
@gobes: I tried, but apparently I don't have enough reputation yet. I will as soon as I have the points, ok?
No problem, I was just saying. BTW, I didn't down vote your answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.