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

20221223232955

新版本的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)

20221223233751

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

smart_cat

你的鼓励将是我写作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值