使用ODBC在SQL C++中返回“停止”返回

使用ODBC在SQL C++中返回“停止”返回,c++,sql,odbc,C++,Sql,Odbc,我的桌子看起来有点像这个 Table cards | CardId | cityName| eventName| Colour| |----------+----------+----------+--------| | 29 | "test" | null | "blue" | | 2 | null | "test | null | 让我们现在说,我知道了 "select * from card where CardId =

我的桌子看起来有点像这个

Table cards
|  CardId  |  cityName| eventName|  Colour|
|----------+----------+----------+--------|
|     29   |   "test" |   null   | "blue" |
|     2    |   null   |  "test   |  null  |
让我们现在说,我知道了

 "select * from card where CardId = 29"
我的返回向量将包含:test,就这样。因此,它将基本上包含eventName之前的所有数据。同样的情况也适用于以下情况

 "select * from card where CardId = 2" 
连接到dB:

的C++代码
void SqlConnection::sqlExecuteSelect(string *select) {

SQLCHAR DBName[20] = "PandemicMain";
SQLCHAR SQLStmt[4000] = { 0 };
SQLRETURN rc = SQL_SUCCESS;
ODBC_Class Example;
if (Example.ConHandle != NULL)

{

    rc = SQLConnect(Example.ConHandle, DBName, SQL_NTS, (SQLCHAR *) "concordia", SQL_NTS, (SQLCHAR *) "University4", SQL_NTS);

    // Allocate An SQL Statement Handle 

    rc = SQLAllocHandle(SQL_HANDLE_STMT, Example.ConHandle, &Example.StmtHandle);

    rc = SQLExecDirect(Example.StmtHandle, SQLStmt, SQL_NTS);

    if (rc == SQL_SUCCESS)

    {

        // Define A SELECT SQL Statement  
        char* finalSelect = new char[select->length() + 1];
        std::strcpy(finalSelect, select->c_str());

        strcpy((char *)SQLStmt, finalSelect);

        // Prepare And Execute The SQL Statement  

            rc = SQLExecDirect(Example.StmtHandle, SQLStmt, SQL_NTS);

        // Display The Results Of The SQL Query  
        if (!rc == SQL_SUCCESS) {
            cout << "*************************** failed ***************" << endl;
        }
        if (rc == SQL_SUCCESS)

        {

            Example.GetResultset();
            Connection.colData = Example.colData;



            // At this point you would want to do something  

            // with the resultset, such as display it.  

        }

    }

    // Free The SQL Statement Handle  

    if (Example.StmtHandle != NULL)

        SQLFreeHandle(SQL_HANDLE_STMT, Example.StmtHandle);

    // Disconnect From The Northwind Sample Database  
    rc = SQLDisconnect(Example.ConHandle);

}
}
Odbc.h

#pragma once

////////////////////////////////////////
#include <windows.h>
#include <sql.h>
#include<sqltypes.h>
#include<sqlext.h>
#include <string>
#include <vector>
#include <iostream>
using namespace std;



// Define The ODBC_Class Class
class ODBC_Class
{
  struct ColDescription
  {
    SQLSMALLINT colNumber;
    SQLCHAR colName[80];
    SQLSMALLINT nameLen;
    SQLSMALLINT dataType;
    SQLULEN colSize;
    SQLSMALLINT decimalDigits;
    SQLSMALLINT nullable;
  };
// Attributes
public:
    SQLHANDLE EnvHandle;
    SQLHANDLE ConHandle;
    SQLHANDLE StmtHandle;
    SQLRETURN rc;
    vector<ColDescription> cols;
    vector< vector<string> > colData;
    // Operations
public:
    ODBC_Class(); // Constructor
    ~ODBC_Class(); // Destructor
    SQLRETURN GetResultset();
    void DescribeColumns();
private:
    _inline SQLRETURN Describe(ColDescription& c);
    SQLRETURN GetColData(int colnum, string& str);
};
Odbc.cpp

 #include "ODBC.h"

//***************************CODE FROM 
http://www.dreamincode.net/forums/topic/127959-odbc-c-example/ 
*************************************/
// Define The ODBC_Class Class


// Define The Class Constructor
ODBC_Class::ODBC_Class()
{
// Initialize The Return Code Variable
rc = SQL_SUCCESS;
// Allocate An Environment Handle
rc = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &EnvHandle);
// Set The ODBC Application Version To 3.x
if (rc == SQL_SUCCESS)
    rc = SQLSetEnvAttr(EnvHandle, SQL_ATTR_ODBC_VERSION,
    (SQLPOINTER)SQL_OV_ODBC3, SQL_IS_UINTEGER);
// Allocate A Connection Handle
if (rc == SQL_SUCCESS)
    rc = SQLAllocHandle(SQL_HANDLE_DBC, EnvHandle, &ConHandle);
}

// Define The Class Destructor
ODBC_Class::~ODBC_Class()
{
// Free The Connection Handle
if (ConHandle != NULL)
    SQLFreeHandle(SQL_HANDLE_DBC, ConHandle);
// Free The Environment Handle
if (EnvHandle != NULL)
    SQLFreeHandle(SQL_HANDLE_ENV, EnvHandle);
}

// Get the data for one column and return the info in the form
// of a std::string.  The ODBC driver will make all necessary
// data conversions from whatever type the data is in the database
// to SQL_CHAR.  You could make this function more comples by 
// getting the return type as it appears in the database then constructing
// a VARIANT object to hold the data.
SQLRETURN ODBC_Class::GetColData(int colnum, string& str)
{
  SQLCHAR buf[255] = { 0 };
  if ((rc = SQLGetData(StmtHandle, colnum, SQL_CHAR, buf, sizeof(buf), NULL)) == SQL_SUCCESS)
      str = reinterpret_cast<char*>(buf);
 return rc;
}

//
// Define The ShowResults() Member Function
SQLRETURN ODBC_Class::GetResultset()
{
   // Get all column description
   DescribeColumns();
   // erase anything that's in the colData vector
   colData.clear();
   // fetch a row from the resultset
   while (SQLFetch(StmtHandle) == SQL_SUCCESS)
   {
       // vector of strings to hold the column data
       vector<string> col;
       string data;
       // column counter
       int i = 1;
       // get the data for each column and add it to 
       // the col vector
       while (GetColData(i, data) == SQL_SUCCESS)
       {
           col.push_back(data);
           ++i; // increment the column number
       }
       // add column data to the colData vector
       colData.push_back(col);
    }
   return SQL_SUCCESS;
  }

 // Get the description for one column in the resultset.
 // This was made a seprate function to simplify the coding
 SQLRETURN  ODBC_Class::Describe(ColDescription& c)
{
    return SQLDescribeCol(StmtHandle, c.colNumber,
         c.colName, sizeof(c.colName), &c.nameLen,
         &c.dataType, &c.colSize, &c.decimalDigits, &c.nullable);
}

// Get the description for all the columns in the resultset.
void ODBC_Class::DescribeColumns()
{
    ColDescription c;
    c.colNumber = 1;
     cols.clear();
    while (Describe(c) == SQL_SUCCESS)
   {
      cols.push_back(c);
       ++c.colNumber;
   }

 }
使用SQLGetDiagRec之后

我得到以下信息:

SqlState:22002

所以我知道这意味着需要指示器变量,但不提供


无论如何要处理这个问题?

我有一阵子也犯了同样的错误。基本上,ODBC试图告诉您正在检索的值为NULL。它将使用SQLGetData中的最后一个参数执行此操作,您可以在此处找到更多信息:

该行:

  if ((rc = SQLGetData(StmtHandle, colnum, SQL_CHAR, buf, sizeof(buf), NULL)) == SQL_SUCCESS)
  str = reinterpret_cast<char*>(buf);

您需要将传递的空值更改为它可以填充的值。如果缓冲区为空值,ODBC将尝试填充该缓冲区。它将始终返回您在此字段中返回的列的长度,但如果您传递NULL,它将不会终止,除非它返回NULL,在这种情况下它需要它。通过ref传入一个SQLLEN,它应该作为SQL NULL数据返回。

实际上,我对ODBC一无所知,只是好奇而已。我的第一个猜测是,你会得到一个字符**和一些指针算法,可以解决你的问题,但:谷歌搜索一点,并提供。看起来,访问select请求的结果并不是很简单。也许,你应该编辑你的问题并展示你的C++代码。MHM好主意。虽然我对C++非常陌生,尤其是SQL的一部分,但是我的SQL连接代码是从一个网站上获取的。我会把它加进去;好主意代码没有显示如何将列绑定到缓冲区以及如何检索数据:使用SqlBindCol或使用SqlGetData。SqlFetch呢?你用什么库/什么是class?啊,我很抱歉。我想我应该只连接到sql。现在就加进去了。感谢您指出,实际上您还需要其他内容的长度字段,例如charN值。请注意,它们是填充的!甚至varchar值。此外,我还更喜欢使用SQL_WCHAR,它可以很容易地转换为std::U16字符串;如果不这样做,SQLGetData将在现代ODBC SQL Server驱动程序中失败。最后一个细节是,如果使用SQL_WCHAR,通常会将长度除以2 UTF-16,这样做…-如果您不检查SQL\u NULL\u数据,-1/2将给出0,因此您将得到一个空字符串,而不是NULL。