绑定参数 ODBCBinding Parameters ODBC

在执行语句前,必须将 SQL 语句中的每个参数关联或绑定到应用程序中的变量。Each parameter in an SQL statement must be associated, or bound, to a variable in the application before the statement is executed. 当应用程序将变量绑定到参数时,它会对驱动程序描述变量地址、C 数据类型等。When the application binds a variable to a parameter, it describes that variable - address, C data type, and so on - to the driver. 还介绍了参数本身-SQL 数据类型、精度等。It also describes the parameter itself - SQL data type, precision, and so on. 驱动程序将此信息存储在它为该语句维护的结构中,并在执行语句时使用该信息检索变量中的值。The driver stores this information in the structure it maintains for that statement and uses the information to retrieve the value from the variable when the statement is executed.

在执行语句之前,可以随时绑定或重新绑定参数。Parameters can be bound or rebound at any time before a statement is executed. 如果在执行语句后重新绑定参数,则在再次执行该语句之前,将不会应用绑定。If a parameter is rebound after a statement is executed, the binding does not apply until the statement is executed again. 若要将参数绑定到不同的变量,应用程序只需使用新变量重新绑定参数;上一个绑定会自动释放。To bind a parameter to a different variable, an application simply rebinds the parameter with the new variable; the previous binding is automatically released.

在将其他变量绑定到参数之前,变量保持绑定到参数,直到通过使用 SQL_RESET_PARAMS 选项调用SQLFreeStmt来解除所有参数的绑定,或直到语句释放。A variable remains bound to a parameter until a different variable is bound to the parameter, until all parameters are unbound by calling SQLFreeStmt with the SQL_RESET_PARAMS option, or until the statement is released. 出于此原因,应用程序必须确保在变量未绑定之前不会将其释放。For this reason, the application must be sure that variables are not freed until after they are unbound. 有关详细信息,请参阅分配和释放缓冲区For more information, see Allocating and Freeing Buffers.

由于参数绑定只是存储在由语句的驱动程序所维护的结构中的信息,因此可按任意顺序进行设置。Because parameter bindings are just information stored in the structure maintained by the driver for the statement, they can be set in any order. 它们还独立于所执行的 SQL 语句。They are also independent of the SQL statement that is executed. 例如,假设应用程序绑定三个参数,然后执行以下 SQL 语句:For example, suppose an application binds three parameters and then executes the following SQL statement:

INSERT INTO Parts (PartID, Description, Price) VALUES (?, ?, ?)  

如果应用程序随后立即执行 SQL 语句If the application then immediately executes the SQL statement

SELECT * FROM Orders WHERE OrderID = ?, OpenDate = ?, Status = ?  

在同一语句句柄上,使用INSERT语句的参数绑定,因为这些是存储在语句结构中的绑定。on the same statement handle, the parameter bindings for the INSERT statement are used because those are the bindings stored in the statement structure. 在大多数情况下,这是一种不太好的编程做法,应避免这样做。In most cases, this is a poor programming practice and should be avoided. 相反,应用程序应调用带有 SQL_RESET_PARAMS 选项的SQLFreeStmt ,以取消所有旧参数的绑定,然后绑定新参数。Instead, the application should call SQLFreeStmt with the SQL_RESET_PARAMS option to unbind all the old parameters and then bind new ones.

本部分包含下列主题。This section contains the following topics.