使用 ODBC 检查列是否自动递增

Check if a column is auto increment with ODBC?

本文关键字:是否 ODBC 检查 使用      更新时间:2023-10-16

有没有办法知道使用C++和ODBC API是否具有具有自动序列属性(AKA标识属性)的列?

提前致谢

您可以使用

SQLSpecialColumns函数。它提供了一个列列表,当事务更新行中的任何值时,这些列会自动更新。

>您可以将 SQLColAttribute 与字段标识符参数一起使用SQL_DESC_AUTO_UNIQUE_VALUE如在此函数中

int fetch_identity(const std::string& sql, int& is_identity)
    {
      SQLHSTMT hstmt;
      is_identity = 0;
      SQLCHAR         colname[32];        // column name
      SQLSMALLINT     coltype;            // column type
      SQLSMALLINT     colnamelen;         // length of column name
      SQLSMALLINT     nullable;           // whether column can have NULL value
      SQLULEN         collen;             // column length
      SQLSMALLINT     decimaldigits;      // no of digits if column is numeric
      SQLLEN          auto_unique_value;;
      SQLINTEGER      idx;
      SQLSMALLINT     nbr_cols;
      if (!SQL_SUCCEEDED(SQLAllocHandle(SQL_HANDLE_STMT, query.m_hdbc, &hstmt)))
      {
      }
      if (!SQL_SUCCEEDED(SQLPrepare(hstmt, (SQLCHAR*)sql.c_str(), SQL_NTS)))
      {
        extract_error(hstmt, SQL_HANDLE_STMT);
      }
      // Get number of nbr_cols from prepared statement
      if (!SQL_SUCCEEDED(SQLNumResultCols(hstmt, &nbr_cols)))
      {
        extract_error(hstmt, SQL_HANDLE_STMT);
      }
      for (idx = 0; idx < nbr_cols; idx++)
      {
        // for each column from the prepared statement in hstmt, get the
        // column name, type, column size, decimal digits, and nullability
        if (!SQL_SUCCEEDED(SQLDescribeCol(hstmt,
          (SQLUSMALLINT)idx + 1,
          colname,
          sizeof(colname),
          &colnamelen,
          &coltype,
          &collen,
          &decimaldigits,
          &nullable)))
        {
          extract_error(hstmt, SQL_HANDLE_STMT);
        }
        auto_unique_value = 0;
        //SQL_DESC_AUTO_UNIQUE_VALUE
        //FieldIdentifier parameter returned in NumericAttributePtr
        //SQL_TRUE if the column is an autoincrementing column.
        //SQL_FALSE if the column is not an autoincrementing column or is not numeric.
        if (!SQL_SUCCEEDED(SQLColAttribute(hstmt,
          (SQLUSMALLINT)idx + 1,
          SQL_DESC_AUTO_UNIQUE_VALUE,
          NULL,
          0,
          NULL,
          &auto_unique_value)))
        {
          extract_error(hstmt, SQL_HANDLE_STMT);
        }
        if (auto_unique_value == 1)
        {
          is_identity = 1;
        }
      }
      SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
      return 0;
    }

变量m_hdbc在此处描述

https://github.com/pedro-vicente/lib_odbc