3

I'm trying to connect to an IBM DB2 database from Python. I'm using Python 3.12.10, SQLAlchemy 1.4.54, and Pandas 2.3.2. This is what my code looks like:

import os
import sqlalchemy
import pandas as pd
from keyring import get_credential

if os.name == "nt":
    os.add_dll_directory(os.path.join(os.getenv("IBM_DB_HOME"), "bin"))

hostname = #my hostname
port = #my port number
database = #my database
engine = sqlalchemy.create_engine(
    f"db2+ibm_db://"
    f"{get_credential('my saved credentials', None).username}"
    f":{get_credential('my saved credentials', None).password}"
    f"@{hostname}:{port}/{database}")

df = pd.read_sql_query(
sql = f"""
      --my SQL query
      ;""",
con = engine)

However, this returns the following error message:

UserWarning: pandas only supports SQLAlchemy connectable (engine/connection) or database string URI or sqlite3 DBAPI2 connection. Other DBAPI2 objects are not tested. Please consider using SQLAlchemy.

Does anyone know why this is happening and what I can do to fix it please? I am using a SQLAlchemy engine for the 'con' parameter in pd.read_sql_query, as the error message advises me to do, so I'm not sure what the problem is. I've confirmed that the hostname, port, database name, and my credentials are all correct.

3
  • it is not error but only warning. And code may still work. Commented Oct 8 at 11:51
  • 1
    Have you run any SELECT statement? Does it work? Commented Oct 8 at 12:17
  • I would recommend extracting the username and password into variables and using a single formatted sting to create the connection string and the engine, like so: sqlalchemy.create_engine(f"db2+ibm_db://{username}:{password}@{hostname}:{port}/{database}") Commented Oct 8 at 12:30

1 Answer 1

3

I've now resolved this. User comments are correct in that the quoted warning was not what was causing the code to fail; it was actually this, further down in the output:

AttributeError: 'Engine' object has no attribute 'connection'

This seems to have been caused by an upgrade in the version of Pandas I was using; apparently the correct syntax for connections has been changed in Pandas 2.2 and up. For more details see here: Pandas to_sql to sqlite returns 'Engine' object has no attribute 'cursor'

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.