Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sqlalchemy: Print contents of table

I want to print all the contents of a table using sqalchemy. I can't seem to figure out how inspect works.

I want to achieve something like that:

column1: value1, column2: value4
column1: value2, column2: value5
column1: value3, column2: value6

In a table that looks like this:

Table_1:
+---------+---------+
| column1 | column2 |
+---------+---------+
| value1  | value4  |
| value2  | value5  |
| value3  | value6  |
+---------+---------+
like image 286
ThP Avatar asked Jul 01 '16 18:07

ThP


2 Answers

While I don't know how to do this with inspect, I achieve the desire output through regular queries. For this example, I created a sqlite table based on your example. First, we connect and reflect on this existing database.

from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy import select
eng = create_engine("sqlite:///databases/example_table.db")

Base = automap_base()
Base.prepare(eng, reflect=True)
Table = Base.classes.example_table

To facilitate our query, we instantiate a session,

Session = sessionmaker(bind=eng)
session = Session()

and perform the query, saving the outcome to result.

stmt = select('*').select_from(Table)
result = session.execute(stmt).fetchall()

The elements of this query are instances of the sqlalchemy RowProxy class, which has a keys method that can be used to access the column names. Consequently, we can transform the result with a few short functions.

def result_dict(r):
    return dict(zip(r.keys(), r))

def result_dicts(rs): 
    return list(map(result_dict, rs))

result_dicts(result)

which returns

[{'id': 1, 'column1': 'value1', 'column2': 'value4'},
 {'id': 2, 'column1': 'value2', 'column2': 'value5'},
 {'id': 3, 'column1': 'value3', 'column2': 'value6'}]
like image 172
yardsale8 Avatar answered Sep 19 '22 11:09

yardsale8


I don't know how useful this might be, but you can visualize the table in desperate times or you need a quick sneak peek at the table.

# create an engine using the following code and 
# replace it with the path to your .db file.

from sqlalchemy import create_engine
engine = create_engine('sqlite:///employee.db', echo = False)

# Import pandas and connect the engine
# use the lowercase representation of your table name for table_name parameter 
# For ex:
class Users(db.Model):
    ...
    ...
    ...

import pandas as pd

user_table = pd.read_sql_table(table_name="users", con=engine)
# This will load the table as dataframe and then you can display

I understand that in case the database is huge, visualizing it using pandas may not be the best idea but as I said above, desperate times !

like image 38
Shreyas Vedpathak Avatar answered Sep 21 '22 11:09

Shreyas Vedpathak