Connecting to DB2 on MacOS with Python

I wanted my first post to be something that really resonated with me, which is why I chose this topic.


If you’ve tried to connect to a DB2 database using the ibm-db package, you might have run into this issue at some point:

ImportError: dlopen(venv/lib/python3.7/site-packages/ibm_db.cpython-37m-darwin.so, 2): Library not loaded: libdb2.dylib

Referenced from: venv/lib/python3.7/site-packages/ibm_db.cpython-37m-darwin.so  Reason: image not found

After hours and even days of Googling, I finally compiled a number of Github issues and Stack overflow posts to come to the solution to this problem.

After hours and even days of Googling, I finally compiled a number of Github issues and Stack overflow posts to come to the solution to this problem.

Here are the steps I used to solve this problem:

  1. Install Python 3.7 via Homebrew. Doing so allows give you a more standard location for the Python3.7 executable
    brew install python@3.7
  2. Make sure you’re using a virtual environment. I primarily use Pycharm IDE, so isolating this issue to a virtual environment made it easier to fix for me.
  3. Activate your virtual environment. If you don’t do this, the below script won’t work
    source venv/bin/activate
  4. Run the following script (https://gist.github.com/dragid10/afb9b16d72c4f7807938bd28c37f6ad3)
# Only need to execute this when running on mac
set -e
py_folder=$(ls venv/lib | head -n 1)
cd "venv/lib/$py_folder/site-packages/"

db2_binary=$(ls ibm_db.cpython* | head -n 1)
echo $db2_binary
install_name_tool -change libdb2.dylib "$(pwd)/clidriver/lib/libdb2.dylib" "$db2_binary"

if test -f "$PWD/clidriver/lib/libdb2.dylib"; then
    rm libdb2.dylib
fi

ln -s "/usr/local/lib/$py_folder/site-packages/clidriver/lib/libdb2.dylib libdb2.dylib"

After this, you should successfully be able to connect to DB2 via Python.

Note, I’ve only had this issue when using Python 3.7 and python 3.8. Testing with Python 3.9,  I don’t have this problem, and don’t need to run this script. Your results may vary