Ошибка sqlallochandle для драйвера в sql handle env
Hi, I have installed sql anywhere 16 in linux machine. Below is the content of my odbc.ini file. I have written the odbc program to access the demo database(which came as part of sql anywhere16 installation). While running the program am getting the error message - "NOTICE: IM004:1:0:[unixODBC][Driver Manager]Driver's SQLAllocHandle on SQL_HANDLE_HENV failed".
Can anyone help me to identify the problem with my settings?
asked 19 Nov '13, 00:00
Vaish
90 ● 4 ● 4 ● 9
accept rate: 0%
Can you show us your code? Which call is getting the error? Which build number (of the ODBC driver) are you using? What bitness are you using - 32 or 64?
;; This buffer is for notes you don't want to save, and for Lisp evaluation. ;; If you want to create a file, visit that file with C-x C-f, ;; then enter the text in that file's own buffer.
Hi , My code is below:
It fails in - SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env); Am working on 32 bit. And the ODBC driver is the one which came along with sqlanywhere16 installation . My Linux distro is - Red Hat Enterprise Linux Server release 5 (Tikanga).
Also, If you could tell me the procedure to run the sample programs given in path - sdk/dbcapi/examples/ in linux, it would be very helpful. My attempt to compilation with this command - gcc -I/home/vaish/sqlanywhere16/sdk/include/ -I/usr/include/ -L/usr/local/lib/ -L/usr/lib/ -Llibdl.so connecting.cpp -o connecting
failed with below errors:
Hi, Basically I need to connect to sybase database in Linux via C programming in linux. I searched on the net and found only tutorial for programming in windows environment/C++ programming. So , If there is any good documentation on connecting sybase in linux C programming , plz share me the link. It will be of great help. Thanks, Vaish
ODBC connection failures
If you do not deploy all the files required for the ODBC driver, you may encounter the following error when attempting to connect to a database.
[IM004][Microsoft][ODBC Driver Manager] Driver's SQLAllocHandle on SQL_HANDLE_ENV failed
Check that you have installed all the files required for the correct operation of the ODBC driver.
answered 19 Nov '13, 11:37
JBSchueler
2.9k ● 2 ● 12 ● 54
accept rate: 19%
PS. I recently added this to the SQL Anywhere documentation. You'll see it in some new release.
Сводка
Функцию SQLAllocHandle выделяет среду, соединение, инструкцию или дескриптор.
Эта функция является универсальной функцией выделения дескрипторов, которые заменяют функции ODBC 2,0 SQLAllocConnect, SQLAllocEnv и SQLAllocStmt. Чтобы разрешить приложениям, вызывающим функцию SQLAllocHandle , работать с ODBC 2. драйверы x , вызов функцию SQLAllocHandle сопоставляется в диспетчере драйверов с SQLAllocConnect, SQLAllocEnv или SQLAllocStmt, в зависимости от ситуации. Дополнительные сведения см. в разделе "Комментарии". Дополнительные сведения о том, что диспетчер драйверов сопоставляет эту функцию при использовании ODBC 3. Приложение x работает с ODBC 2. драйвер x см. в разделе Сопоставление функций замены для обратной совместимости приложений.
Синтаксис
Аргументы
SQL_HANDLE_DBC_INFO_TOKENный обработчик используется только диспетчером драйверов и драйвером. Приложения не должны использовать этот тип обработчика. Дополнительные сведения о SQL_HANDLE_DBC_INFO_TOKEN см. в разделе Разработка осведомленности Connection-Pool в драйвере ODBC.
аутпусандлептр
Проверки Указатель на буфер, в который будет возвращен маркер для вновь выделенной структуры данных.
Возвращаемое значение
SQL_SUCCESS, SQL_SUCCESS_WITH_INFO, SQL_INVALID_HANDLE или SQL_ERROR.
При выделении маркера, отличного от обработчика среды, если функцию SQLAllocHandle возвращает SQL_ERROR, он устанавливает аутпусандлептр в значение SQL_NULL_HDBC, SQL_NULL_HSTMT или SQL_NULL_HDESC в зависимости от значения параметром handletype, если только аргумент OUTPUT не является пустым указателем. Затем приложение может получить дополнительные сведения из структуры диагностических данных, связанной с маркером в аргументе инпусандле .
Ошибки выделения памяти для обработчиков среды
Выделение среды выполняется как в диспетчере драйверов, так и в пределах каждого драйвера. Ошибка, возвращаемая функцией функцию SQLAllocHandle с параметром handletype SQL_HANDLE_ENV, зависит от уровня, в котором произошла ошибка.
Если диспетчеру драйверов не удается выделить память для * аутпусандлептр при вызове функцию SQLAllocHandle с параметром handletype SQL_HANDLE_ENV или если приложение предоставляет указатель null для аутпусандлептр, функцию SQLAllocHandle возвращает SQL_ERROR. Диспетчер драйверов устанавливает для *аутпусандлептр значение SQL_NULL_HENV (если только приложение не предоставил пустой указатель, который возвращает SQL_ERROR). Отсутствует Handle, с помощью которого можно связать дополнительные диагностические сведения.
Диспетчер драйверов не вызывает функцию выделения среды на уровне драйвера, пока приложение не вызовет SQLConnect, SQLBrowseConnect или SQLDriverConnect. Если ошибка возникает в функции функцию SQLAllocHandle на уровне драйвера, то функция SQLConnect, SQLBrowseConnect или SQLDriverConnect диспетчера драйверов возвращает SQL_ERROR. Структура диагностических данных содержит значение SQLSTATE IM004 (сбой драйвера функцию SQLAllocHandle ). Ошибка возвращается для маркера соединения.
Дополнительные сведения о потоке вызовов функций между диспетчером драйверов и драйвером см. в разделе Функция SQLConnect.
Диагностика
Когда функцию SQLAllocHandle возвращает SQL_ERROR или SQL_SUCCESS_WITH_INFO, связанное значение SQLSTATE может быть получено путем вызова SQLGetDiagRec с соответствующим параметром handletype и Handle , для которых задано значение инпусандле. Для аргумента аутпусандле могут возвращаться SQL_SUCCESS_WITH_INFO (но не SQL_ERROR). В следующей таблице перечислены значения SQLSTATE, обычно возвращаемые функцией функцию SQLAllocHandle , и объясняется каждый из них в контексте этой функции. Нотация "(DM)" предшествует описаниям SQLSTATE, возвращаемым диспетчером драйверов. Код возврата, связанный с каждым значением SQLSTATE, имеет SQL_ERROR, если не указано иное.
Комментарии
Функцию SQLAllocHandle используется для выделения дескрипторов для сред, соединений, инструкций и дескрипторов, как описано в следующих разделах. Общие сведения об дескрипторах см. в разделе Handles.
Если драйвер поддерживает несколько выделений, то в каждый момент времени может быть выделено более одной среды, соединения или маркера инструкций. В ODBC ограничение на количество дескрипторов среды, соединения, инструкций или дескрипторов, которые могут быть выделены одновременно, не определено. Драйверы могут накладывать ограничение на количество определенных типов маркеров, которые могут быть выделены одновременно. Дополнительные сведения см. в документации по драйверу.
Если приложение вызывает функцию SQLAllocHandle с * аутпусандлептр , для которого задана среда, соединение, инструкция или дескриптор дескриптора, который уже существует, драйвер перезаписывает сведения, связанные с дескриптором, если только приложение не использует пул соединений (см. раздел "выделение атрибута среды для пулов соединений" Далее в этом разделе). Диспетчер драйверов не проверяет, используется ли уже указанный в * аутпусандлептр обработчик , а также не проверяет предыдущее содержимое маркера перед его перезаписыванием.
Неправильное программирование приложений ODBC для вызова функцию SQLAllocHandle в два раза с той же переменной приложения, определенной для * Аутпусандлептр , без вызова SQLFreeHandle для освобождения обработчика перед перераспределением. Перезапись дескрипторов ODBC таким образом может привести к несогласованному поведению или ошибкам в части драйверов ODBC.
В операционных системах, поддерживающих несколько потоков, приложения могут использовать одну среду, соединение, инструкцию или дескриптор в разных потоках. Поэтому драйверы должны поддерживать защищенный многопоточный доступ к этим сведениям. одним из способов достичь этого, например, является использование критического раздела или семафора. Дополнительные сведения о потоках см. в разделе Многопоточность.
Функцию SQLAllocHandle не устанавливает атрибут среды SQL_ATTR_ODBC_VERSION при вызове для выделения маркера среды; приложение должно быть установлено атрибутом среды, или значение SQLSTATE HY010 (ошибка последовательности функций) будет возвращаться при вызове функцию SQLAllocHandle для выделения маркера соединения.
Для приложений, соответствующих стандартам, функцию SQLAllocHandle сопоставляется с склаллочандлестд во время компиляции. Разница между этими двумя функциями заключается в том, что склаллочандлестд устанавливает атрибут среды SQL_ATTR_ODBC_VERSION SQL_OV_ODBC3 при вызове с аргументом параметром handletype , для которого задано значение SQL_HANDLE_ENV. Это делается потому, что приложения, соответствующие стандартам, всегда имеют формат ODBC 3. приложения x . Более того, для этих стандартов не требуется регистрация версии приложения. Это единственное различие между этими двумя функциями. в противном случае они идентичны. Склаллочандлестд сопоставляется с функцию SQLAllocHandle в диспетчере драйверов. Таким образом, сторонние драйверы не должны реализовывать склаллочандлестд.
Приложения ODBC 3,8 должны использовать:
Функцию SQLAllocHandle, а не склаллочандлестд , чтобы выделить маркер среды.
SQLSetEnvAttr , чтобы присвоить атрибуту среды SQL_ATTR_ODBC_VERSION значение SQL_OV_ODBC3_80.
Выделение дескриптора среды
Дескриптор среды предоставляет доступ к глобальной информации, такой как допустимые дескрипторы соединений и активные дескрипторы подключений. Общие сведения о дескрипторах среды см. в разделе дескрипторы среды.
Чтобы запросить обработчик среды, приложение вызывает функцию SQLAllocHandle с параметром handletype SQL_HANDLE_ENV и инпусандле SQL_NULL_HANDLE. Драйвер выделяет память для сведений о среде и передает значение связанного с ним маркера обратно в аргумент * аутпусандлептр . Приложение передает значение * аутпусандле во всех последующих вызовах, требующих аргумента обработчика среды. Дополнительные сведения см. в разделе Выделение маркера среды.
Если в обработчике среды диспетчера драйверов уже существует обработчик среды драйвера, функцию SQLAllocHandle с параметром handletype SQL_HANDLE_ENV не вызывается в этом драйвере при подключении, только функцию SQLAllocHandle с параметром handletype SQL_HANDLE_DBC. Если обработчик окружения драйвера не существует в обработчике диспетчера драйверов, то при подключении к драйверу первого маркера подключения среды в драйвере функцию SQLAllocHandle с параметром handletype SQL_HANDLE_ENV и функцию SQLAllocHandle с параметром handletype SQL_HANDLE_DBC.
Когда диспетчер драйверов обрабатывает функцию функцию SQLAllocHandle с параметром handletype SQL_HANDLE_ENV, она проверяет ключевое слово Trace в разделе [ODBC] сведений о системе. Если задано значение 1, диспетчер драйверов включает трассировку для текущего приложения. Если установлен флаг трассировки, трассировка запускается, когда первый обработчик среды выделяется и заканчивается при освобождении последнего обработчика среды. Дополнительные сведения см. в разделе Настройка источников данных.
После выделения обработчика среды приложение должно вызвать SQLSetEnvAttr в обработчике среды, чтобы задать атрибут среды SQL_ATTR_ODBC_VERSION. Если этот атрибут не задан до вызова функцию SQLAllocHandle для выделения маркера соединения в среде, вызов для выделения соединения ВОЗВРАТИТ значение SQLSTATE HY010 (ошибка последовательности функций). Дополнительные сведения см. в разделе Объявление версии ODBC приложения.
Выделение общих сред для пула подключений
Среды могут совместно использоваться несколькими компонентами в одном процессе. Общая среда может использоваться более чем одним компонентом одновременно. Если компонент использует общую среду, он может использовать соединения в составе пула, что позволяет распределять и использовать существующее соединение без повторного создания этого соединения.
Перед выделением общей среды, которую можно использовать для пула соединений, приложение должно вызвать SQLSetEnvAttr , чтобы задать SQL_CP_ONE_PER_DRIVER или SQL_CP_ONE_PER_HENV атрибуту среды SQL_ATTR_CONNECTION_POOLING. SQLSetEnvAttr в этом случае вызывается с параметром енвиронменсандле , для которого задано значение null, что делает атрибут атрибутом уровня процесса.
После включения пула соединений приложение вызывает функцию SQLAllocHandle с аргументом параметром handletype , для которого задано значение SQL_HANDLE_ENV. Среда, выделенная этим вызовом, будет неявной общей средой, так как включена поддержка пулов соединений.
При выделении общей среды используемая среда не определяется до тех пор, пока не будет вызван функцию SQLAllocHandle с параметром handletype из SQL_HANDLE_DBC. На этом этапе диспетчер драйверов пытается найти существующую среду, соответствующую атрибутам среды, запрошенным приложением. Если такой среды не существует, она создается как общая среда. Диспетчер драйверов поддерживает счетчик ссылок для каждой общей среды. При первом создании среды счетчику присваивается значение 1. Если найдена соответствующая среда, в приложение возвращается маркер этой среды, а число ссылок увеличивается. Выделенный таким образом обработчик среды можно использовать в любой функции ODBC, которая принимает в качестве входного аргумента обработчик среды.
Выделение дескриптора соединения
Дескриптор соединения предоставляет доступ к таким сведениям, как допустимые операторы и дескрипторы дескрипторов для соединения, а также указывает, открыта ли транзакция в данный момент. Общие сведения о дескрипторах подключений см. в разделе Handles Connections.
Чтобы запросить обработчик соединения, приложение вызывает функцию SQLAllocHandle с параметром handletype SQL_HANDLE_DBC. Аргументу инпусандле присваивается маркер среды, возвращенный вызовом функцию SQLAllocHandle , который выделил этот обработчик. Драйвер выделяет память для сведений о соединении и передает значение связанного с ним маркера обратно в * аутпусандлептр. Приложение передает значение * аутпусандлептр во всех последующих вызовах, для которых требуется маркер подключения. Дополнительные сведения см. в разделе Выделение маркера подключения.
Диспетчер драйверов обрабатывает функцию функцию SQLAllocHandle и вызывает функцию функцию SQLAllocHandle драйвера, когда приложение вызывает SQLConnect, SQLBrowseConnect или SQLDriverConnect. (Дополнительные сведения см. в разделе Функция SQLConnect.)
Если атрибут среды SQL_ATTR_ODBC_VERSION не задан до вызова функцию SQLAllocHandle для выделения маркера соединения в среде, вызов для выделения соединения ВОЗВРАТИТ значение SQLSTATE HY010 (ошибка последовательности функций).
Когда приложение вызывает функцию SQLAllocHandle с аргументом инпусандле , для которого задано значение SQL_HANDLE_DBC а также задает общий обработчик среды, диспетчер драйверов пытается найти существующую общую среду, соответствующую атрибутам среды, заданным приложением. Если такой среды не существует, создается одна из них со счетчиком ссылок (поддерживаемым диспетчером драйверов), равным 1. Если найдена соответствующая общая среда, этот маркер возвращается приложению, а его число ссылок увеличивается.
Фактическое соединение, которое будет использоваться, не определяется диспетчером драйверов до тех пор, пока не будет вызван SQLConnect или SQLDriverConnect . Диспетчер драйверов использует параметры соединения в вызове SQLConnect (или ключевые слова подключения в вызове SQLDriverConnect) и атрибуты соединения, заданные после выделения соединения, чтобы определить, какое подключение в пуле следует использовать. Дополнительные сведения см. в разделе Функция SQLConnect.
Выделение дескриптора инструкции
чтобы запросить маркер инструкции, приложение подключается к источнику данных, а затем вызывает функцию sqlallochandle перед отправкой инструкций SQL. В этом вызове параметром handletype должно быть установлено в значение SQL_HANDLE_STMT и инпусандле должны быть установлены в маркер соединения, возвращенный вызовом функцию SQLAllocHandle , который выделил этот обработчик. Драйвер выделяет память для данных инструкции, связывает обработчик инструкции с указанным соединением и передает значение связанного с ним обработчика обратно в * аутпусандлептр. Приложение передает значение * аутпусандлептр во всех последующих вызовах, требующих маркер оператора. Дополнительные сведения см. в разделе Выделение маркера инструкции.
Когда дескриптор инструкции выводится, драйвер автоматически выделяет набор из четырех дескрипторов и назначает дескрипторы для таких дескрипторов атрибутам операторов SQL_ATTR_APP_ROW_DESC, SQL_ATTR_APP_PARAM_DESC, SQL_ATTR_IMP_ROW_DESC и SQL_ATTR_IMP_PARAM_DESC. Они называются неявно выделенными дескрипторами. Сведения о том, как явно выделить дескриптор приложения, см. в следующем разделе "Выделение дескриптора дескриптора".
Выделение дескриптора дескриптора
Когда приложение вызывает функцию SQLAllocHandle с параметром handletype SQL_HANDLE_DESC, драйвер выделяет дескриптор приложения. Они называются явно выделенными дескрипторами. Приложение направляет драйвер для использования явно выделенного дескриптора приложения вместо автоматического выделения единицы для данного дескриптора инструкции путем вызова функции SQLSetStmtAttr с атрибутом SQL_ATTR_APP_ROW_DESC или SQL_ATTR_APP_PARAM_DESC. Дескриптор реализации не может быть выделен явным образом, а в вызове функции SQLSetStmtAttr нельзя указывать дескриптор реализации.
Явно выделенные дескрипторы связаны с дескриптором соединения вместо дескриптора оператора (так как автоматически назначаемые дескрипторы). Дескрипторы остаются выделены только тогда, когда приложение фактически подключается к базе данных. Так как явно выделенные дескрипторы связаны с дескриптором соединения, приложение может связать явно выделенный дескриптор с более чем одной инструкцией в пределах соединения. Неявно выделенный дескриптор приложения, с другой стороны, не может быть связан с более чем одним дескриптором инструкции. (Он не может быть связан с каким-либо другим маркером инструкции, который был выделен для.) Явно выделенные дескрипторы дескриптора можно освободить явным образом либо с помощью приложения, либо путем вызова SQLFreeHandle с параметром handletype SQL_HANDLE_DESC или неявно при закрытии соединения.
При освобождении явно выделенного дескриптора, неявно выделенный дескриптор снова связывается с инструкцией. (Атрибут SQL_ATTR_APP_ROW_DESC или SQL_ATTR_APP_PARAM_DESC для этой инструкции снова задается неявно выделенным дескриптором дескриптора.) Это справедливо для всех инструкций, которые были связаны с явно выделенным дескриптором в соединении.
Summary
SQLAllocHandle allocates an environment, connection, statement, or descriptor handle.
This function is a generic function for allocating handles that replaces the ODBC 2.0 functions SQLAllocConnect, SQLAllocEnv, and SQLAllocStmt. To allow applications calling SQLAllocHandle to work with ODBC 2.x drivers, a call to SQLAllocHandle is mapped in the Driver Manager to SQLAllocConnect, SQLAllocEnv, or SQLAllocStmt, as appropriate. For more information, see "Comments." For more information about what the Driver Manager maps this function to when an ODBC 3.x application is working with an ODBC 2.x driver, see Mapping Replacement Functions for Backward Compatibility of Applications.
Syntax
Arguments
HandleType
[Input] The type of handle to be allocated by SQLAllocHandle. Must be one of the following values:
SQL_HANDLE_DBC_INFO_TOKEN handle is used only by the Driver Manager and driver. Applications should not use this handle type. For more information about SQL_HANDLE_DBC_INFO_TOKEN, see Developing Connection-Pool Awareness in an ODBC Driver.
InputHandle
[Input] The input handle in whose context the new handle is to be allocated. If HandleType is SQL_HANDLE_ENV, this is SQL_NULL_HANDLE. If HandleType is SQL_HANDLE_DBC, this must be an environment handle, and if it is SQL_HANDLE_STMT or SQL_HANDLE_DESC, it must be a connection handle.
OutputHandlePtr
[Output] Pointer to a buffer in which to return the handle to the newly allocated data structure.
Returns
SQL_SUCCESS, SQL_SUCCESS_WITH_INFO, SQL_INVALID_HANDLE, or SQL_ERROR.
When allocating a handle other than an environment handle, if SQLAllocHandle returns SQL_ERROR, it sets OutputHandlePtr to SQL_NULL_HDBC, SQL_NULL_HSTMT, or SQL_NULL_HDESC, depending on the value of HandleType, unless the output argument is a null pointer. The application can then obtain additional information from the diagnostic data structure associated with the handle in the InputHandle argument.
Environment Handle Allocation Errors
Environment allocation occurs both within the Driver Manager and within each driver. The error returned by SQLAllocHandle with a HandleType of SQL_HANDLE_ENV depends on the level in which the error occurred.
If the Driver Manager cannot allocate memory for *OutputHandlePtr when SQLAllocHandle with a HandleType of SQL_HANDLE_ENV is called, or the application provides a null pointer for OutputHandlePtr, SQLAllocHandle returns SQL_ERROR. The Driver Manager sets *OutputHandlePtr to SQL_NULL_HENV (unless the application provided a null pointer, which returns SQL_ERROR). There is no handle with which to associate additional diagnostic information.
The Driver Manager does not call the driver-level environment handle allocation function until the application calls SQLConnect, SQLBrowseConnect, or SQLDriverConnect. If an error occurs in the driver-level SQLAllocHandle function, then the Driver Manager-level SQLConnect, SQLBrowseConnect, or SQLDriverConnect function returns SQL_ERROR. The diagnostic data structure contains SQLSTATE IM004 (Driver's SQLAllocHandle failed). The error is returned on a connection handle.
For more information about the flow of function calls between the Driver Manager and a driver, see SQLConnect Function.
Diagnostics
When SQLAllocHandle returns SQL_ERROR or SQL_SUCCESS_WITH_INFO, an associated SQLSTATE value can be obtained by calling SQLGetDiagRec with the appropriate HandleType and Handle set to the value of InputHandle. SQL_SUCCESS_WITH_INFO (but not SQL_ERROR) can be returned for the OutputHandle argument. The following table lists the SQLSTATE values typically returned by SQLAllocHandle and explains each one in the context of this function; the notation "(DM)" precedes the descriptions of SQLSTATEs returned by the Driver Manager. The return code associated with each SQLSTATE value is SQL_ERROR, unless noted otherwise.
Comments
SQLAllocHandle is used to allocate handles for environments, connections, statements, and descriptors, as described in the following sections. For general information about handles, see Handles.
More than one environment, connection, or statement handle can be allocated by an application at a time if multiple allocations are supported by the driver. In ODBC, no limit is defined on the number of environment, connection, statement, or descriptor handles that can be allocated at any one time. Drivers may impose a limit on the number of a certain type of handle that can be allocated at a time; for more information, see the driver documentation.
If the application calls SQLAllocHandle with *OutputHandlePtr set to an environment, connection, statement, or descriptor handle that already exists, the driver overwrites the information associated with the handle, unless the application is using connection pooling (see "Allocating an Environment Attribute for Connection Pooling" later in this section). The Driver Manager does not check to see whether the handle entered in *OutputHandlePtr is already being used, nor does it check the previous contents of a handle before overwriting them.
It is incorrect ODBC application programming to call SQLAllocHandle two times with the same application variable defined for *OutputHandlePtr without calling SQLFreeHandle to free the handle before reallocating it. Overwriting ODBC handles in such a manner could lead to inconsistent behavior or errors on the part of ODBC drivers.
On operating systems that support multiple threads, applications can use the same environment, connection, statement, or descriptor handle on different threads. Drivers must therefore support safe, multithread access to this information; one way to achieve this, for example, is by using a critical section or a semaphore. For more information about threading, see Multithreading.
SQLAllocHandle does not set the SQL_ATTR_ODBC_VERSION environment attribute when it is called to allocate an environment handle; the environment attribute must be set by the application, or SQLSTATE HY010 (Function sequence error) will be returned when SQLAllocHandle is called to allocate a connection handle.
For standards-compliant applications, SQLAllocHandle is mapped to SQLAllocHandleStd at compile time. The difference between these two functions is that SQLAllocHandleStd sets the SQL_ATTR_ODBC_VERSION environment attribute to SQL_OV_ODBC3 when it is called with the HandleType argument set to SQL_HANDLE_ENV. This is done because standards-compliant applications are always ODBC 3.x applications. Moreover, the standards do not require the application version to be registered. This is the only difference between these two functions; otherwise, they are identical. SQLAllocHandleStd is mapped to SQLAllocHandle inside the driver manager. Therefore, third-party drivers do not have to implement SQLAllocHandleStd.
ODBC 3.8 applications should use:
SQLAllocHandle and not SQLAllocHandleStd to allocate an environment handle.
SQLSetEnvAttr to set the SQL_ATTR_ODBC_VERSION environment attribute to SQL_OV_ODBC3_80.
Allocating an Environment Handle
An environment handle provides access to global information such as valid connection handles and active connection handles. For general information about environment handles, see Environment Handles.
To request an environment handle, an application calls SQLAllocHandle with a HandleType of SQL_HANDLE_ENV and an InputHandle of SQL_NULL_HANDLE. The driver allocates memory for the environment information and passes the value of the associated handle back in the *OutputHandlePtr argument. The application passes the *OutputHandle value in all subsequent calls that require an environment handle argument. For more information, see Allocating the Environment Handle.
Under a Driver Manager's environment handle, if there already exists a driver's environment handle, then SQLAllocHandle with a HandleType of SQL_HANDLE_ENV is not called in that driver when a connection is made, only SQLAllocHandle with a HandleType of SQL_HANDLE_DBC. If a driver's environment handle does not exist under the Driver Manager's environment handle, both SQLAllocHandle with a HandleType of SQL_HANDLE_ENV and SQLAllocHandle with a HandleType of SQL_HANDLE_DBC are called in the driver when the first connection handle of the environment is connected to the driver.
When the Driver Manager processes the SQLAllocHandle function with a HandleType of SQL_HANDLE_ENV, it checks the Trace keyword in the [ODBC] section of the system information. If it is set to 1, the Driver Manager enables tracing for the current application. If the trace flag is set, tracing starts when the first environment handle is allocated and ends when the last environment handle is freed. For more information, see Configuring Data Sources.
After allocating an environment handle, an application must call SQLSetEnvAttr on the environment handle to set the SQL_ATTR_ODBC_VERSION environment attribute. If this attribute is not set before SQLAllocHandle is called to allocate a connection handle on the environment, the call to allocate the connection will return SQLSTATE HY010 (Function sequence error). For more information, see Declaring the Application's ODBC Version.
Allocating Shared Environments for Connection Pooling
Environments can be shared among multiple components on a single process. A shared environment can be used by more than one component at the same time. When a component uses a shared environment, it can use pooled connections, which allow it to allocate and use an existing connection without re-creating that connection.
Before allocating a shared environment that can be used for connection pooling, an application must call SQLSetEnvAttr to set the SQL_ATTR_CONNECTION_POOLING environment attribute to SQL_CP_ONE_PER_DRIVER or SQL_CP_ONE_PER_HENV. SQLSetEnvAttr in this case is called with EnvironmentHandle set to null, which makes the attribute a process-level attribute.
After connection pooling has been enabled, an application calls SQLAllocHandle with the HandleType argument set to SQL_HANDLE_ENV. The environment allocated by this call will be an implicit shared environment because connection pooling has been enabled.
When a shared environment is allocated, the environment that will be used is not determined until SQLAllocHandle with a HandleType of SQL_HANDLE_DBC is called. At that point, the Driver Manager tries to find an existing environment that matches the environment attributes requested by the application. If no such environment exists, one is created as a shared environment. The Driver Manager maintains a reference count for each shared environment; the count is set to 1 when the environment is first created. If a matching environment is found, the handle of that environment is returned to the application and the reference count is incremented. An environment handle allocated in this manner can be used in any ODBC function that accepts an environment handle as an input argument.
Allocating a Connection Handle
A connection handle provides access to information such as the valid statement and descriptor handles on the connection and whether a transaction is currently open. For general information about connection handles, see Connection Handles.
To request a connection handle, an application calls SQLAllocHandle with a HandleType of SQL_HANDLE_DBC. The InputHandle argument is set to the environment handle that was returned by the call to SQLAllocHandle that allocated that handle. The driver allocates memory for the connection information and passes the value of the associated handle back in *OutputHandlePtr. The application passes the *OutputHandlePtr value in all subsequent calls that require a connection handle. For more information, see Allocating a Connection Handle.
The Driver Manager processes the SQLAllocHandle function and calls the driver's SQLAllocHandle function when the application calls SQLConnect, SQLBrowseConnect, or SQLDriverConnect. (For more information, see SQLConnect Function.)
If the SQL_ATTR_ODBC_VERSION environment attribute is not set before SQLAllocHandle is called to allocate a connection handle on the environment, the call to allocate the connection will return SQLSTATE HY010 (Function sequence error).
When an application calls SQLAllocHandle with the InputHandle argument set to SQL_HANDLE_DBC and also set to a shared environment handle, the Driver Manager tries to find an existing shared environment that matches the environment attributes set by the application. If no such environment exists, one is created, with a reference count (maintained by the Driver Manager) of 1. If a matching shared environment is found, that handle is returned to the application and its reference count is incremented.
The actual connection that will be used is not determined by the Driver Manager until SQLConnect or SQLDriverConnect is called. The Driver Manager uses the connection options in the call to SQLConnect (or the connection keywords in the call to SQLDriverConnect) and the connection attributes set after connection allocation to determine which connection in the pool should be used. For more information, see SQLConnect Function.
Allocating a Statement Handle
A statement handle provides access to statement information, such as error messages, the cursor name, and status information for SQL statement processing. For general information about statement handles, see Statement Handles.
To request a statement handle, an application connects to a data source and then calls SQLAllocHandle before it submits SQL statements. In this call, HandleType should be set to SQL_HANDLE_STMT and InputHandle should be set to the connection handle that was returned by the call to SQLAllocHandle that allocated that handle. The driver allocates memory for the statement information, associates the statement handle with the specified connection, and passes the value of the associated handle back in *OutputHandlePtr. The application passes the *OutputHandlePtr value in all subsequent calls that require a statement handle. For more information, see Allocating a Statement Handle.
When the statement handle is allocated, the driver automatically allocates a set of four descriptors and assigns the handles for these descriptors to the SQL_ATTR_APP_ROW_DESC, SQL_ATTR_APP_PARAM_DESC, SQL_ATTR_IMP_ROW_DESC, and SQL_ATTR_IMP_PARAM_DESC statement attributes. These are referred to as implicitly allocated descriptors. To allocate an application descriptor explicitly, see the following section, "Allocating a Descriptor Handle."
Allocating a Descriptor Handle
When an application calls SQLAllocHandle with a HandleType of SQL_HANDLE_DESC, the driver allocates an application descriptor. These are referred to as explicitly allocated descriptors. The application directs a driver to use an explicitly allocated application descriptor instead of an automatically allocated one for a given statement handle by calling the SQLSetStmtAttr function with the SQL_ATTR_APP_ROW_DESC or SQL_ATTR_APP_PARAM_DESC attribute. An implementation descriptor cannot be allocated explicitly, nor can an implementation descriptor be specified in an SQLSetStmtAttr function call.
Explicitly allocated descriptors are associated with a connection handle instead of a statement handle (as automatically allocated descriptors are). Descriptors remain allocated only when an application is actually connected to the database. Because explicitly allocated descriptors are associated with a connection handle, an application can associate an explicitly allocated descriptor with more than one statement within a connection. An implicitly allocated application descriptor, on the other hand, cannot be associated with more than one statement handle. (It cannot be associated with any statement handle other than the one that it was allocated for.) Explicitly allocated descriptor handles can be freed explicitly either by the application or by calling SQLFreeHandle with a HandleType of SQL_HANDLE_DESC, or implicitly when the connection is closed.
When the explicitly allocated descriptor is freed, the implicitly allocated descriptor is again associated with the statement. (The SQL_ATTR_APP_ROW_DESC or SQL_ATTR_APP_PARAM_DESC attribute for that statement is again set to the implicitly allocated descriptor handle.) This is true for all statements that were associated with the explicitly allocated descriptor on the connection.
I have an excel (2003) macro that connects to a DB2 connection via ODBC:
Dim db As ADODB.Connection
Dim rs As ADODB.Recordset
Set db = New ADODB.Connection
Set rs = New ADODB.Recordset
Set db = New Connection
db.CursorLocation = adUseClient
db.Properties("Prompt") = adPromptCompleteRequired
db.CommandTimeout = 240
db.ConnectionTimeout = 240
db.Open Range("BASE2")
Set rs = New Recordset
rs.Open sql, db
But when I execute this code I keep getting an error message: [Microsoft] [ODBC Driver Manager] Driver's SQLAllocHandle on SQL_HANDLE_ENV failed.
I am running a Windows 7 (64 bits), IBM DB2 (v9). I have also configured the system DNS to use a 32 bits driver (in order to avoid the architecture mismatch error). And I have added my USER to the SQLLIB folder permission with full control option.
Even with all this things set, I keep getting this error message. Anyone know how to solve this problem? I am out of options here.
Thanks in advance.
Answers
I don't know what is being used as the connection string. the website below says not to use ODBC (has known bug) but instead use oldb. You are setting a new connection which is using a default connection string. You can see what the connection string is by adding a watch for the variable db and looking at the connection property.
You also have two connection string (see below)
Set db = New ADODB.Connection
Set rs = New ADODB.Recordset
Set db = New Connection ****** Remove this line
If deleting the one line doesn't work then I would changing the open statement.
From : db.Open ConnectionString:=Range("BASE2")
To : db.Open ConnectionString:="Provider=SQLOLEDB;Data Source=" & Range("BASE2")
To : db.Open ConnectionString:="Provider=SQLOLEDB;Data Source=Range(""BASE2"")"
All replies
You probably don't have any connection. Where did you find the statement below?
I have never seen a connection open string like this before. Is there any examples or websites you have been using?
You also having set sql to any valid command string
sql needs to contain at minimum the following
sql = "Select * from MyTable"
Thanks for the reply
But this is not the problems really, this logic works on Windows XP, the error appeared when the OS was changed to Windows 7.
Just to clarify: This excel I am using have a series of drop downs that a user can select. Depending on the information selected on these drop down lists a different sql is executed under a certain DB2 Connection.
db.Open Range("BASE2")
BASE2: is a defined name range that stores the connection name (the same name defined on the ODBC under system DNS and the same name for the connection set on DB2).
rs.Open sql, db
sql: is a variable that contains the sql depending on the settings.
sql = Replace(sql, "", Range("Owner"))
sql = Replace(sql, "", Range("Year"))
From some other forum I have been reading, it seems this error is related to Windows permissions. But none of the solutions (to guarantee enough permission level for the SQLLIB folder (DB2 folder)) seems to be working on my case.
I mean, I am able to run queries and pull information. It is just that it is not working when I am trying to do it from this excel tool. I am wondering if could be a driver version issue, but which driver I do not know.
The microsoft jet engine is used to as the drive for opening databases including excel. I can't tell if the problem is with the connection or the sql statement. I would make sure the connection is valid by add the variable db to the watch window by highlighting the variable with the mouse and then right click and select Add Watch.
The step through the code and make sure the connection is valid by checking the db variable properties in the watch window and check for errors. Next I would do the same with the sql variable and the rs variable. Make sure the SQL statement is correct.
The microsoft jet engine is used to as the drive for opening databases including excel. I can't tell if the problem is with the connection or the sql statement. I would make sure the connection is valid by add the variable db to the watch window by highlighting the variable with the mouse and then right click and select Add Watch.
The step through the code and make sure the connection is valid by checking the db variable properties in the watch window and check for errors. Next I would do the same with the sql variable and the rs variable. Make sure the SQL statement is correct.
jdweng
I did the Add Watch and double checked the SQL statement. Nothing is wrong with th SQL. Also, nothing I have read regading this specific error message leads me to conclude that the problem was in the SQL Statement.
Definitely this is a permission issue, I am just not sure which folder I am forgetting to add the correct permission.
Since some time between Tuesday afternoon (7 May) and Wednesday morning (8 May), European time, all attempts to connect to our SQL Server database through PHP (specifically PDO) fail with the following error message:
We have both an SQL Server database and a MySQL database running, and both are accessed from both PHP and Classic ASP (VBScript). Of these four constellations, only PHP connecting to the SQL Server database fails; the other three combinations work as they always have.
- Updated PHP 7.1 to version 7.1.29.
- Updated Microsoft ODBC Driver 17 for SQL Server to version 17.3.1.1.
- Removed Microsoft ODBC Driver 13 for SQL Server from the default set of components.
- Updated Microsoft Drivers for PHP 7.1/7.2 for SQL Server to version 5.6.1.
When I check the ODBC (64-bit) drivers on the server, I get this:
It looks to me like there are three different ODBC drivers for SQL Server installed; I don’t know how to figure out which is being used with PDO to connect to SQL Server. Version 173.01.01 is, I take it, version 17.3.1.1, so that does seem to have been updated – I don’t know what version we had before. phpinfo() informed me that pdo_sqlsrv was version 5.2.0+10712, but that turned out to be because it was using the 32-bit extension, rather than the 64-bit extension (probably a manual error by me originally). After switching to the 64-bit version, pdo_sqlsrv is now version 5.6.1+11919, which fits with the changelog – but the connection error remains.
If ODBC Driver 13 was supposed to have been removed in the update, though, it clearly wasn’t, as the screenshot shows – but what exactly does “from the default set of components” mean anyway? Does that affect existing installs?
I’ve been researching and trying to find some kind of idea about what’s actually causing the SQLSTATE error, and the closest thing I’ve found is this GitHub issue from January, which seems to deal with a similar issue. The suggested fix there is to uninstall all previous versions of ODBC and install only the most recent one (17.2 in that issue, 17.3 now), but I can’t tell if that includes versions 11 and 13. At any rate, our msodbcsql17.dll file on the server is dated to 14 February, so I suspect this is perhaps not the cause of the current issue.
Apart from that one GitHub issue, I’ve come up completely empty-handed. I’ve been banging my head against the Internet wall all day, and I’ve nothing to show for it but a headache and an ended tether.
Can someone help me troubleshoot this? Am I barking up the wrong tree with the Plesk update? Might it be something else? Halp!
Читайте также:
- Программа для компьютера кроссворд
- Javascript размеры прокрутка и координаты элементов на странице и окна браузера
- Какое количество информации получит пользователь при сообщении что нужная ему программа 128 дисков
- Где в 1с 8 3 бухгалтерия настроить график работы
- На компьютере обнаружен файл уплотненного диска или программа кэширования