如何从 ODBC 连接 SQLConnect?

How to connect with SQLConnect from ODBC?

我正在尝试使用 ODBC 和 C++ 连接到 SQL 服务器,但它无法连接,我不知道为什么。 DSN 是 已在用户 DSN 列表中设置。

# include "stdafx.h"
# include <windows.h>
# include <stdio.h>
# include <stdlib.h>
# include <sql.h>
# include <sqlext.h>
# include <iostream>
 
int main( )
{
    HENV henv;
    HDBC hdbc;
    RETCODE rc;
    
    SQLAllocEnv(&henv);
    SQLAllocConnect(henv, &hdbc);
 
    /* Connect to the database using the ODBC DSN definition. */
    rc = SQLConnect( hdbc,     /* Connection handle */
        (SQLWCHAR*)"db1",      /* The ODBC DSN definition */
        SQL_NTS,               /* This is a null-terminated string */
        NULL,                  /* No username required */
        0,                     /* This is a null-terminated string */
        NULL,                  /* No password required */
        0);                    /* This is a null-terminated string */

    if ((rc != SQL_SUCCESS) && (rc != SQL_SUCCESS_WITH_INFO))
    {
        SQLFreeConnect(hdbc);
        SQLFreeEnv(henv);
        std::cout << "FAIL\n";
    }
    else{
        SQLFreeConnect(hdbc);
        SQLFreeEnv(henv);
        std::cout << "YEA! \n";
    }

    /* Exit this program. */
    system("pause");
    return( 0 );
}

解决方法: 在将其提供给 SQLConnect 之前需要声明变量类型并设置其值。 感谢 PaulMcKenzie。


    SQLWCHAR name [] = L"db1";
    
    rc = SQLConnect( hdbc,     /* Connection handle */
        name,                  /* The ODBC DSN definition */
        SQL_NTS,               /* This is a null-terminated string */
        NULL,                  /* No username required */
        0,                     /* This is a null-terminated string */
        NULL,                  /* No password required */
        0);                    /* This is a null-terminated string */

这不会像你想的那样:

(SQLWCHAR*)"db1",

如果 SQLWCHAR* 是指向宽字符的指针,则转换非宽字符串文字不会产生所需的结果,因为转换不会神奇地将非宽字符串文字转换为宽字符串。由于 "db1" 字符串在函数接收字符串时以某种方式结束不正确,ODBC 函数失败。


处理这个问题的正确方法是首先让代码在没有任何字符串类型到字符串类型转换的情况下进行编译。转换字符串类型是可能出错的标志。使用函数需要的字符串类型。

这适用于任何应用程序——如果您正在转换字符串类型,您最好确切地知道您在做什么,因为您可能通过发出 C 风格的转换来扼杀编译器来规避 C++ 的类型安全错误。

在本例中,字符串类型为 SQLWCHAR,因此可以创建一个字符串(在本例中,可修改,因为它不是 const 指针):

SQLWCHAR name [] = L"db1";

然后函数将不需要对第二个参数进行强制转换:

rc = SQLConnect( hdbc,     /* Connection handle */
    name,                  /* The ODBC DSN definition */
    SQL_NTS,               /* This is a null-terminated string */
    NULL,                  /* No username required */
    0,                     /* This is a null-terminated string */
    NULL,                  /* No password required */
    0);