pythonvisual-studiodb2

Unable to connect DB2 Database with Python in Visual Studio


I have installed Python 3.12.5 and Visual studio in Windows. I have followed the steps mentioned in the link https://github.com/ibmdb/python-ibmdb/blob/master/INSTALL.md (Step 1) . Executed the below command,

pip install ibm_db
import ibm_db >> this resulted in error ImportError: DLL load failed while importing ibm_db: The specified module could not be found

Executed the below commands to overcome the error in python

import os
os.add_dll_directory('C:\\Python\\Python312\\Lib\\site-packages\\clidriver\\bin')
import ibm_db

Tried to execute the below code in visual studio and resulted in error ImportError: DLL load failed while importing ibm_db: The specified module could not be found

import ibm_db
ibm_db.connect("DATABASE=name;HOSTNAME=host;PORT=60000;PROTOCOL=TCPIP;UID=username;
            PWD=password;", "", "")
print('connection successful')

I'm not sure whether I'm missing any step as I tried to execute import ibm_db from python still it results in the same error.


Solution

  • The solution, per the comments , involved correctly placing the lines: import os os.add_dll_directory(....) import ibm_db into the python-script being run.

    Additionally it is necessary that the import ibm_db line throws no exceptions, it must succeed before python ibm_db can operate.

    This workaround became necessary only after ibm_db release 3.2.3 and the README describes this on the github page for python ibm_db, and the issues lists describe the rationale for this change. It's unclear if this will be a permanent change or whether subsequent future improvements make it unnecessary.

    The directory given to os.add_dll_directory() should be the full path to the location of the clidriver bin subdirectory. This can be different on every machine and can vary with virtual environments, and vary with python versions.

    One way to find the directory name is to use pip show ibm_db and examine the "Location:" line and append the "bin" directory. When specifying the directory-path replace the Microsoft-Windows directory separator character (backslash) with a (double backslash).

    You can also use a few more lines of python to search for the clidriver directory in the site-packages folder of your current python or virtual-environment and dynamically construct the location and appending the "bin" subdirectory and pass the dynamically constructed path to the os.add_dll_directory. This avoids hard-coding the path. You can also make that code conditional on the operating system being MS-Windows (as the python script might also be required to run on linux which does not use os.add_dll_directory(), so as to allow your python script to work on different operating systems from the same source-code.