I recently sent some working code from my laptop to my desktop. Even though they are both using the same tech (Visual studio community 15 and SQL Server 14) I am unable to connect to my database on the desktop.
I've got an identical ODBC driver on both (and have tried various combinations on my desktop). Whilst controlling the connection from the ODBC to SQL Server it seems fine, but when I run my application from the debugger I receive this error:
Message: [Microsoft][ODBC Driver Manager] Connection Not Open
SQLSTATE: 08003 Failed to connect
This is the code:
#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <sqltypes.h>
#include <sql.h>
#include <sqlext.h>
using namespace std;
void show_error(unsigned int handletype, const SQLHANDLE& handle)
{
SQLWCHAR sqlstate[1024];
SQLWCHAR message[1024];
if (SQL_SUCCESS == SQLGetDiagRec(handletype, handle, 1, sqlstate, NULL, message, 1024, NULL))
wcout << "Message: " << message << "\nSQLSTATE: " << sqlstate << endl;
}
int main() {
SQLHENV env;
SQLHDBC dbc;
SQLHSTMT stmt;
SQLRETURN ret;
SQLSMALLINT columns;
int row = 0;
/* Allocate an environment handle */
SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env);
/* We want ODBC 3 support */
SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (void *)SQL_OV_ODBC3, 0);
/* Allocate a connection handle */
SQLAllocHandle(SQL_HANDLE_DBC, env, &dbc);
/* Connect to the DSN */
SQLDriverConnectW(dbc, NULL, L"DRIVER={SQL Server};ERA-PC-STUART\\JBK_DB;DATABASE=master;UID=geo;PWD=kalle123;", SQL_NTS, NULL, 0, NULL, SQL_DRIVER_COMPLETE);
/* Check for success */
if (SQL_SUCCESS != SQLAllocHandle(SQL_HANDLE_STMT, dbc, &stmt))
{
show_error(SQL_HANDLE_DBC, dbc);
std::cout << "Failed to connect";
}
if (SQL_SUCCESS != SQLExecDirectW(stmt, L"select salary from dbo.salary_table", SQL_NTS)) {
show_error(SQL_HANDLE_STMT, stmt);
}
else {
int id;
cout << "ID:" << endl;
while (SQLFetch(stmt) == SQL_SUCCESS) {
SQLGetData(stmt, 1, SQL_C_ULONG, &id, 0, NULL);
cout << id << endl;
}
}
return 0;
}
As mentioned the code runs flawlessly on my laptop, but for some reason it won't work on the desktop - even though the ODBC connects.
SQLDriverConnect
and fetch the error-information if establishing the connection does not succeed. Usually, those error-messages contain quite useful information to narrow down the problem. - ergSQLDriverConnect
you do not check the return value. You should already get anSQL_ERROR
there, and you can then feed the connection-handle to the error-function. - ergret = SQLDriverConnectW(dbc, NULL, L"DRIVER={SQL Server};ERA-PC-STUART\\JBK_DB;DATABASE=master;UID=geo;PWD=kalle123;", SQL_NTS, NULL, 0, NULL, SQL_DRIVER_COMPLETE); if(!SQL_SUCCEEDED(ret)) { show_error(SQL_HANDLE_DBC, dbc); }
- erg