如何为SQLAlchemy多数据库绑定创建Engine生成Pandas DataFrame?
解决方法
首先先修正你配置里的两处错误,这可能是导致你失败的核心原因:
- 主数据库的配置键写错了,应该是
SQLALCHEMY_DATABASE_URI,不是SQLALCHEMY_DATABASE+URI - 绑定库'two'的URI里
3306 /tvshow多了空格,要改成3306/tvshow,否则数据库连接会报错
接下来,你不需要重新手动拼接URI创建Engine,直接从已初始化的db对象中获取对应数据库的Engine即可:
获取对应Engine的方式
- 主数据库(movie库)的Engine:直接使用
db.engine,这是SQLAlchemy默认绑定的主库引擎 - 绑定数据库'two'(tvshow库)的Engine:调用
db.get_engine(app, bind='two'),通过绑定键获取对应引擎
修改后的完整代码如下:
from flask import Flask from flask_sqlalchemy import SQLAlchemy from sqlalchemy import Column, VARCHAR, INTEGER import pandas as pd app = Flask(__name__) # 修正配置键名和URI空格问题 app.config['SQLALCHEMY_DATABASE_URI'] = \ "mariadb+mariadbconnector://harold:password@localhost:3306/movie?charset=utf8mb4" app.config['SQLALCHEMY_BINDS'] = \ {'two' : "mariadb+mariadbconnector://harold:password@localhost:3306/tvshow?charset=utf8mb4"} db = SQLAlchemy(app) class Movie(db.Model): __tablename__ = "movie" movie_id = Column(VARCHAR(length=25), primary_key=True, nullable=False) title = Column(VARCHAR(length=255), nullable=False) series_id = Column(VARCHAR(length=25), nullable=False) rel_date = Column(VARCHAR(length=25), nullable=False) class TVShow(db.Model): __bind_key__ = 'two' __tablename__ = "tvshow" tv_id = Column(VARCHAR(length=25), primary_key=True, nullable=False) name = Column(VARCHAR(length=255), nullable=False) seasons = Column(INTEGER, nullable=False) episodes = Column(INTEGER, nullable=False) def set_df(): # 主库直接使用默认引擎 main1_df = pd.read_sql_table('movie', db.engine) # 通过绑定键获取第二个库的引擎 two_engine = db.get_engine(app, bind='two') main2_df = pd.read_sql_table('tvshow', two_engine) return main1_df, main2_df
如果你想脱离Flask的db对象手动创建Engine,也可以直接用SQLAlchemy的create_engine方法提取配置中的URI:
from sqlalchemy import create_engine # 主库Engine main_engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI']) # 绑定库Engine two_engine = create_engine(app.config['SQLALCHEMY_BINDS']['two'])
两种方式都能正确获取对应数据库的Engine,传入pd.read_sql_table后即可成功将表转换为Pandas DataFrame。
内容的提问来源于stack exchange,提问作者Harold Meneley
相关产品推荐
相关产品推荐

