title: C++ ODBC SQL Server 2008 Connection
body: <p>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.</p>
  
  <p>I am using Microsoft Visual Studio 2010, creating a Win32 Console App as a blank project and adding main.cpp myself.</p>
  
  <p>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.</p>
  
  <p>However in C++ I just can't get a connection, it's always reporting as failed.</p>
  
  <p>My code so far is as follows</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;windows.h&gt;
  #include &lt;sqltypes.h&gt;
  #include &lt;sql.h&gt;
  #include &lt;sqlext.h&gt;
  
  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, &amp;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, &amp;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, &amp;stmt))
      {
          std::cout &lt;&lt; "Failed to connect";
      }
  
      std::cin.get();
      return 0;
  }
  </code></pre>
  
  <p>I've based this on seeing a few online examples such as <a href="http://www.easysoft.com/developer/languages/c/odbc_tutorial.html" rel="nofollow">http://www.easysoft.com/developer/languages/c/odbc_tutorial.html</a></p>
  
  <p>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.</p>
  
  <p>What am I doing wrong here please? Thanks</p>