句柄数

句柄是标识特定项的不透明的 32 位值;在 ODBC 中,此项目可以是环境、连接、语句或描述符。 当应用程序调用 SQLAllocHandle 时,驱动程序管理器或驱动程序将创建指定类型的新项目,并将其句柄返回到应用程序。 应用程序稍后使用句柄在调用 ODBC 函数时标识该项目。 驱动程序管理器和驱动程序使用句柄查找有关项目的信息。

例如,以下代码使用两个语句句柄(hstmtOrderhstmtLine)来标识创建销售订单结果集和销售订单行号的语句。 稍后,它会使用这些句柄来标识要从中提取数据的结果集。

SQLHSTMT      hstmtOrder, hstmtLine; // Statement handles.  
SQLUINTEGER   OrderID;  
SQLINTEGER    OrderIDInd = 0;  
SQLRETURN     rc;  
  
// Prepare the statement that retrieves line number information.  
SQLPrepare(hstmtLine, "SELECT * FROM Lines WHERE OrderID = ?", SQL_NTS);  
  
// Bind OrderID to the parameter in the preceding statement.  
SQLBindParameter(hstmtLine, 1, SQL_PARAM_INPUT, SQL_C_ULONG, SQL_INTEGER, 5, 0,  
               &OrderID, 0, &OrderIDInd);  
  
// Bind the result sets for the Order table and the Lines table. Bind  
// OrderID to the OrderID column in the Orders table. When each row is  
// fetched, OrderID will contain the current order ID, which will then be  
// passed as a parameter to the statement tofetch line number  
// information. Code not shown.  
  
// Create a result set of sales orders.  
SQLExecDirect(hstmtOrder, "SELECT * FROM Orders", SQL_NTS);  
  
// Fetch and display the sales order data. Code to check if rc equals  
// SQL_ERROR or SQL_SUCCESS_WITH_INFO not shown.  
while ((rc = SQLFetch(hstmtOrder)) != SQL_NO_DATA) {  
   // Display the sales order data. Code not shown.  
  
   // Create a result set of line numbers for the current sales order.  
   SQLExecute(hstmtLine);  
  
   // Fetch and display the sales order line number data. Code to check  
   // if rc equals SQL_ERROR or SQL_SUCCESS_WITH_INFO not shown.  
   while ((rc = SQLFetch(hstmtLine)) != SQL_NO_DATA) {  
      // Display the sales order line number data. Code not shown.  
   }  
  
   // Close the sales order line number result set.  
   SQLCloseCursor(hstmtLine);  
}  
  
// Close the sales order result set.  
SQLCloseCursor(hstmtOrder);  

句柄仅对创建它们的 ODBC 组件有意义;也就是说,只有驱动程序管理器可以解释驱动程序管理器句柄,只有驱动程序可以解释自己的句柄。

例如,假设前面的示例中的驱动程序分配一个结构来存储有关语句的信息,并将指向此结构的指针作为语句句柄返回。 当应用程序调用 SQLPrepare 时,它将传递 SQL 语句和用于销售订单行号的语句的句柄。 驱动程序将 SQL 语句发送到数据源,数据源会对其进行准备并返回访问计划标识符。 驱动程序使用句柄查找存储此标识符的结构。

稍后,当应用程序调用 SQLExecute 以生成特定销售订单的行号结果集时,它将传递相同的句柄。 驱动程序使用句柄从结构中检索访问计划标识符。 它将标识符发送到数据源中,以告知要执行哪个计划。

ODBC 有两个级别的句柄:驱动程序管理器句柄和驱动程序句柄。 应用程序在调用 ODBC 函数时使用驱动程序管理器句柄,因为它在驱动程序管理器中调用这些函数。 驱动程序管理器使用此句柄查找相应的驱动程序句柄,在调用驱动程序中的函数时使用驱动句柄。 有关如何使用驱动程序和驱动程序管理器句柄的示例,请参阅驱动程序管理器在连接过程中的角色

有两个级别的句柄这一情况是 ODBC 体系结构的项目;在大多数情况下,它与应用程序或驱动程序无关。 尽管通常没有理由这样做,但应用程序可以通过调用 SQLGetInfo 来确定驱动程序句柄。

本部分包含以下主题。