Pandas告警UserWarning: pandas only supports SQLAlchemy connectable

Pandas告警UserWarning: pandas only supports SQLAlchemy connectable

  • 一、报错信息
  • 二、老的书写方式
  • 三、新的书写方式

一、报错信息

使用老的书写方式从数据库导入数据到pandas, 会打出一条warning信息:

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.

二、老的书写方式

老的书写方式为:

import pymysql
import pandas as pd

db_host = 'localhost'
user = 'root'
passwd = '123456'
db = 'mytestdb'

conn = pymysql.connect(host=db_host,
                       user=user,
                       passwd=passwd,
                       db=db,
                       charset='utf8')

sql = 'SELECT * FROM students'

pd.set_option('display.unicode.ambiguous_as_wide', True)
pd.set_option('display.unicode.east_asian_width', True)
df = pd.read_sql(sql, conn)
print(df)

conn.close()

三、新的书写方式

按照提示,推荐使用SQLAlchemy,需要先安装SQLAlchemy库:

pip install sqlalchemy

Pandas告警UserWarning: pandas only supports SQLAlchemy connectable_第1张图片

新版本的pandas库中con参数使用sqlalchemy库创建的create_engine对象 。创建create_engine对象(格式类似于URL地址)

from sqlalchemy import create_engine
import pandas as pd

MYSQL_HOST = 'localhost'
MYSQL_PORT = '3306'
MYSQL_USER = 'root'
MYSQL_PASSWORD = '123456'
MYSQL_DB = 'mytestdb'

engine = create_engine('mysql+pymysql://%s:%s@%s:%s/%s?charset=utf8'
                           % (MYSQL_USER, MYSQL_PASSWORD, MYSQL_HOST, MYSQL_PORT, MYSQL_DB))

sql = 'SELECT * FROM students'

df = pd.read_sql(sql, engine)

pd.set_option('display.unicode.ambiguous_as_wide', True)
pd.set_option('display.unicode.east_asian_width', True)
print(df)

Pandas告警UserWarning: pandas only supports SQLAlchemy connectable_第2张图片

你可能感兴趣的:(疑难杂症,pandas,python,数据挖掘,开发语言,数据库)