Can Sqlalchemy work well with multiple attached SQLite database files?

后端 未结 1 1619
深忆病人
深忆病人 2021-02-06 09:41

It\'s possible to connect multiple SQLite databases together using the \'ATTACH\' statement and work with them jointly. Tables in each SQLite file can be referenced using a sch

相关标签:
1条回答
  • 2021-02-06 09:48

    Create Engine of SQlite with inmemory than attach different database files

    from sqlalchemy import create_engine, MetaData, Table,Column,Integer,select
    from sqlalchemy.orm import mapper, sessionmaker
    from sqlite3 import dbapi2 as sqlite
    from sqlalchemy.engine.reflection import Inspector
    
    class Bookmarks(object):
        pass
    
    class BookmarksB(object):
        pass
    
    
    
    def loadSession():
        engine = create_engine('sqlite://', echo=True)
        engine.execute("attach database 'database_b' as BB;")
        engine.execute("attach database 'database_a' as AA;")
        metadata = MetaData(engine)
    
    
        inspector = Inspector.from_engine(engine)
        print inspector.get_table_names()
    
        moz_bookmarks = Table('table_a', metadata,Column("id", Integer, primary_key=True),schema='AA', autoload=True)
        mapper(Bookmarks, moz_bookmarks)
        moz_bookmarksB = Table('table_b', metadata,Column("id", Integer, primary_key=True),schema='BB', autoload=True)
        mapper(BookmarksB, moz_bookmarksB)
    
        Session = sessionmaker(bind=engine)
        session = Session()
        return session
    
    if __name__ == "__main__":
        session = loadSession()
        res = session.query(Bookmarks).all()
        for m in res:
            print m.msisdn,m.id
    
        #print list(select([moz_bookmarks, moz_bookmarksB], moz_bookmarks.c.b_id == moz_bookmarksB.c.id).execute())
    
    0 讨论(0)
提交回复
热议问题