It is a good programming practice to free handles. However, for simplicity, the following sample does not include code that frees allocated handles. For an example of how to free handles, see SQLFreeHandle Function.
// SQLFreeStmt.cpp
// compile with: user32.lib odbc32.lib
#include <windows.h>
#include <sqlext.h>
int main() {
// declare and initialize the environment, connection, statement handles
SQLHENV henv = NULL; // Environment
SQLHDBC hdbc = NULL; // Connection handle
SQLHSTMT hstmt = NULL; // Statement handle
SQLRETURN retCode;
HWND desktopHandle = GetDesktopWindow(); // desktop's window handle
SQLCHAR connStrbuffer[1024];
SQLSMALLINT connStrBufferLen;
retCode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
retCode = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, -1);
retCode = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);
retCode = SQLSetConnectAttr(hdbc, SQL_LOGIN_TIMEOUT, (SQLPOINTER)10, 0);
retCode = SQLDriverConnect(hdbc, desktopHandle, (SQLCHAR *)"Driver={SQL Server}", SQL_NTS, connStrbuffer, 1024 + 1, &connStrBufferLen, SQL_DRIVER_PROMPT);
retCode = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);
retCode = SQLFreeStmt(hstmt, SQL_CLOSE);
retCode = SQLFreeStmt(hstmt, SQL_UNBIND);
retCode = SQLFreeStmt(hstmt, SQL_RESET_PARAMS);
}