Uri
Uri

Reputation: 2257

Trying to connect to an SQL Server 2000 database through ODBC with C, problems on SQLConnect

I'm having trouble connecting to an SQL Server 2000 database using C. The program compiles but I get an error when connecting to the database. More specifically, "resultado" gets a value of -1.
This is the code:

#include <stdlib.h>
#include <stdio.h>
#include <windows.h>
#include <sqlext.h>

int main(int argc, char *argv[])
{
    SQLHANDLE environmentHandle;
    SQLHANDLE connectionHandle;

    //Connecting to the Database
    SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &environmentHandle);
    SQLSetEnvAttr(environmentHandle, SQL_ATTR_ODBC_VERSION, (void*) SQL_OV_ODBC3, 0);
    SQLAllocHandle(SQL_HANDLE_DBC, environmentHandle, &connectionHandle);
    SQLSetConnectAttr(connectionHandle, SQL_LOGIN_TIMEOUT,(void*)  5, 0);
    SQLCHAR serverName[60]; strcpy((char*) serverName,"SERVERSUCURSAL\0");
    SQLCHAR userName[60];   strcpy((char*) userName, "sa\0");
    SQLCHAR passWord[60];   strcpy((char*) passWord, "syntelsol\0");
    SQLRETURN resultado = SQLConnect(connectionHandle,serverName, strlen((char*)serverName), userName, 
         strlen((char*)userName), passWord, strlen((char*)passWord));

    //Creamos las sentencias
    SQLHANDLE statementHandle; 

    //Liberamos las handles 
    SQLDisconnect(connectionHandle);
    SQLFreeHandle(SQL_HANDLE_DBC, connectionHandle);
    SQLFreeHandle(SQL_HANDLE_ENV, environmentHandle);

    return 0;
}

This is what the database looks like . The server name is likely SERVERSUCURSAL:
https://i.sstatic.net/LDzQp.png
Databases

Upvotes: 0

Views: 571

Answers (1)

bohica
bohica

Reputation: 5992

The string you pass as ServerName to SQLConnect should be the name of a Data Source (DSN) which you need to create in the ODBC Administrator. It cannot just be the name of your SQL Server machine/database etc. Open ODBC Administrator and create a data source for MS SQL Server which points to your server.

BTW, you don't need to end all your strings with an extra NUL character either - not that it makes a difference here.

Upvotes: 1

Related Questions