Reputation: 669
I'm trying to connect to a local SQL Server 2008 instance from a newly created C++ app. I am still learning C++, so I might be missing something obvious.
I am using Microsoft Visual Studio 2010, creating a Win32 Console App as a blank project and adding main.cpp myself.
The SQL Server instance is up and running, I can connect to it from other machines using either SQL or Integrated Authentication, I can even get my C# applications to connect using the .net objects.
However in C++ I just can't get a connection, it's always reporting as failed.
My code so far is as follows
#include <iostream>
#include <windows.h>
#include <sqltypes.h>
#include <sql.h>
#include <sqlext.h>
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};SERVER=(local)\DB1;DATABASE=master;UID=sa;PWD=password;", SQL_NTS, NULL, 0, NULL, SQL_DRIVER_COMPLETE);
/* Check for success */
if(SQL_SUCCESS!=SQLAllocHandle(SQL_HANDLE_STMT, dbc, &stmt))
{
std::cout << "Failed to connect";
}
std::cin.get();
return 0;
}
I've based this on seeing a few online examples such as http://www.easysoft.com/developer/languages/c/odbc_tutorial.html
Always, my code is entering to Failed to connect block, even with valid credentials. And trying to use extract_error from the linked article above, produces me no error message at all.
What am I doing wrong here please? Thanks
Upvotes: 3
Views: 12630
Reputation: 63015
Reposting from comments so question can be closed:
(SQLWCHAR*)
is a glaring error. Try L
instead to make your string literal a wide string literal.
The default connection timeout is 60 seconds, so you're probably running into that. Check your SQL protocol settings, and if it's configured to use TCP locally, check your firewall settings as well.
Upvotes: 5