C ++ ODBC SQL Server 2008连接 [英] C++ ODBC SQL Server 2008 Connection

查看:547
本文介绍了C ++ ODBC SQL Server 2008连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试从新创建的C ++应用程序连接到本地SQL Server 2008实例。我仍然在学习C ++,所以我可能会缺少一些明显的东西。

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.

我使用Microsoft Visual Studio 2010,创建一个Win32控制台应用程序作为一个空白项目和添加主。

I am using Microsoft Visual Studio 2010, creating a Win32 Console App as a blank project and adding main.cpp myself.

SQL Server实例已启动并正在运行,我可以使用SQL或集成身份验证从其他计算机连接到它,我甚至可以将我的C#应用​​程序使用.net对象连接。

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.

但是在C ++中,我无法获取连接,总是报告失败。

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;
}



我基于这个看到一些在线的例子,如 http://www.easysoft.com/developer/languages/c/odbc_tutorial.html

始终,我的代码进入失败的连接块,即使有有效的凭据。并尝试使用extract_error从上面的链接文章,产生我没有错误消息。

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

推荐答案

从评论重新发布,因此可以关闭问题:


  • (SQLWCHAR *)是一个明显的错误。尝试 L ,以使您的字符串文字成为字符串文字。

  • (SQLWCHAR*) is a glaring error. Try L instead to make your string literal a wide string literal.

默认连接超时是60秒,所以你可能会遇到这种情况。检查您的SQL协议设置,如果配置为在本地使用TCP,请检查您的防火墙设置。

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.

这篇关于C ++ ODBC SQL Server 2008连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆