Share via


處理

控制代碼是不透明的 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 來判斷驅動程式控制代碼。

此章節包含下列主題。