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 pymysqlimport pandas as pddb_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库中con参数使用sqlalchemy库创建的create_engine对象 。创建create_engine对象(格式类似于URL地址)

from sqlalchemy import create_engineimport pandas as pdMYSQL_HOST = 'localhost'MYSQL_PORT = '3306'MYSQL_USER = 'root'MYSQL_PASSWORD = '123456'MYSQL_DB = 'mytestdb'engine = create_engine('mysql+pymysql://%s:%s@%s:%s/%s" />