sqlalchemy orm使用两个数据库创建mysql Dataframe

mfpqipee  于 2023-02-07  发布在  Mysql
关注(0)|答案(1)|浏览(120)
app = Flask(__name__)
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', engine1)
    main2_df = pd.read_sql_table('tvshow', engine2)

那么,我如何指定哪个数据库用于con/engine呢?我需要从两个表中创建 Dataframe 。
我试过使用完整的sqlalchemy_database_uri,没有成功。试过使用两个数据库,没有成功。我必须做引擎吗?怎么做?

bxgwgixi

bxgwgixi1#

在MySQL/MariaDB中,“database”和“schema”的意思是一样的,所以如果两个数据库都在同一台服务器上,我们可以使用schema=来指定数据库名称。

import pandas as pd
import sqlalchemy as sa

# make default database some other one (just for illustration)
engine = sa.create_engine("mysql://scott:tiger@localhost:3307/mydb", echo=True)

main1_df = pd.read_sql_table("movie", engine, schema="movie")
"""
SELECT movie.movie.id, … FROM movie.movie
"""

main2_df = pd.read_sql_table("tvshow", engine, schema="tvshow")
"""
SELECT tvshow.tvshow.id, … FROM tvshow.tvshow
"""

相关问题