List database tables with SQLAlchemy

前端 未结 4 1284
心在旅途
心在旅途 2020-12-13 01:52

I want to implement a function that gives information about all the tables (and their column names) that are present in a database (not only those created with SQLAlchemy).

4条回答
  •  甜味超标
    2020-12-13 02:18

    While reflection/inspection is useful, I had trouble getting the data out of the database. I found sqlsoup to be much more user-friendly. You create the engine using sqlalchemy and pass that engine to sqlsoup.SQlSoup. ie:

    import sqlsoup
    
    def create_engine():
        from sqlalchemy import create_engine
        return create_engine(f"mysql+mysqlconnector://{database_username}:{database_pw}@{database_host}/{database_name}")
    
    def test_sqlsoup():
        engine = create_engine()
        db = sqlsoup.SQLSoup(engine)
        # Note: database must have a table called 'users' for this example
        users = db.users.all()
        print(users)
    
    if __name__ == "__main__":
        test_sqlsoup()
    

    If you're familiar with sqlalchemy then you're familiar with sqlsoup. I've used this to extract data from a wordpress database.

提交回复
热议问题