Question

Im using the SQLAPI++ to connect my program to a database.

The following code does compile without errors. However it doesn't connect to the database. I get an error saying:

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)
ExecuteNonQuery requires an open and available Connection. 
The connection's current state is closed.

I've checked remote connections are enabled on my server and that TCI/IP is enabled. I've'' also tried adding a port exception to the firewall, failing that I even tried turning the firewall off. -And my antivirus.

So I believe this is something to do with my code. Can anyone find anything wrong?

#include <iostream>
#include "SQLAPI\include\SQLAPI.h"
#include <string>
#include <Windows.h>


using namespace std;

int main(int argc, char* argv[])
{

SAConnection con; 

try
{ 
    con.Connect(

    "BLAKE\\SQLEXPRESS@ERP",     // db *& server?!*
        "sa",   // user
        "blake",   // password
    SA_SQLServer_Client);



}
catch (SAException &x)
{
    // SAConnection::Rollback()

    try
    {
        // on error rollback changes
        con.Rollback();
    }
    catch (SAException &)
    {
    }

    cerr << (const char*)(x.ErrText()) << endl;

}



return 0;
}
Was it helpful?

Solution

First you'll probably want to disable named pipes as a protocol, and force connectivity over TCP/IP only.

After that, as you have an instance name specified, you'll need to open two firewall ports up. One for the SQL Browser Service, which tells SQL clients what port instances of SQL are running on, and one for SQL Server itself. The port named instances run on is random by default (hence the need for the browser service which listens on a fixed port), but you can change this to a fixed port.

You also need to make sure the SQL browser service is running in the first place.

You can also stick the port SQL is listening on into your connection string for the server specification, e.g. server\instance,port. This means you dint need the direct connection to the browser service.

OTHER TIPS

This exception throws when your sqlServer service is stopped or when your TCP port is changed, so check for that one.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top