Osca
Osca

Reputation: 1694

Hide pandas warning: SQLAlchemy

I want to hide this warning UserWarning: pandas only support SQLAlchemy connectable(engine/connection) ordatabase string URI or sqlite3 DBAPI2 connectionother DBAPI2 objects are not tested, please consider using SQLAlchemy and I've tried

import warnings
warnings.simplefilter(action='ignore', category=UserWarning)

import pandas

but the warning still shows.

My python script read data from databases. I'm using pandas.read_sql for SQL queries and psycopg2 for db connections.

Also I'd like to know which line triggers the warning.

Upvotes: 5

Views: 20168

Answers (5)

Ohumeronen
Ohumeronen

Reputation: 2086

Its absolutely ok to ignore warnings if you get the job done. Don't forget to reset warnings.

import warnings

def your_function():
    warnings.simplefilter(action='ignore', category=UserWarning)
    # YOUR pyodbc-Code goes here.
    warnings.simplefilter("always")  # Reset warnings.

Upvotes: 0

Waleed Alfaris
Waleed Alfaris

Reputation: 145

I was having the same error when using psycopg2 to connect to a PostgreSQL database. I was able to successfully hide this warning with the follwing lines:

import warnings
warnings.simplefilter(action='ignore', category=UserWarning)

I think they key here is that UserWarning needs to be a class and not a string like you have in your example.

Hopefully this works for you.

Upvotes: 2

Osca
Osca

Reputation: 1694

I tried this and it doesn't work.

import warnings
warnings.filterwarnings('ignore')

Therefore, I used SQLAlchemy (as the warning message wants me to do so) to wrap the psycopg2 connection.

I followed the instruction here: SQLAlchemy for psycopg2 documentation

A simple example:

import psycopg2
import sqlalchemy
import pandas as pd

conn = sqlalchemy.create_engine(f"postgresql+psycopg2://{user}:{pw}@{host}:{port}/{db}")

query = "select count(*) from my_table"

pd.read_sql(query, conn)

The warning doesn't get triggered anymore.

Upvotes: 9

Mattdroidvita123
Mattdroidvita123

Reputation: 59

Using the following worked well for me:

import warnings

warnings.filterwarnings('ignore').

I am using pandas with pyodbc and was previously getting the same warning.

Upvotes: 5

Timothy
Timothy

Reputation: 153

The warnings that you're filtering right now are warnings of type FutureWarning. The warning that you're getting is of type UserWarning, so you should change the warning category to UserWarning. I hope this answers your question regarding why pandas is giving that warning.

Upvotes: 1

Related Questions