SQLAlchemy Core Select


This entry is part 4 of 6 in the series SQLAlchemy

How do we read data from a SQLite database in Python using SQLAlchemy Core?

  • From previous projects, we have an existing database and a table in that database
  • We also have a small bit of data in the table
  • Database is D:\Test\emp4.db’
  • Table is Employees
  • It has 3 columns: id, name and position
import sqlalchemy as sa
engine = sa.create_engine(r'sqlite:///D:\Test\emp4.db') 
connection = engine.connect()

meta_data = sa.MetaData()

employees = sa.Table('Employees', meta_data, autoload_with=engine)

# SQL is "SELECT * FROM Employees"
query = sa.select([employees])
result = connection.execute(query)
result_set = result.fetchall()
print(result_set)
new_query = employees.select().where(employees.c.id==4)  # c is alias for columns
result = connection.execute(new_query)
result_set = result.fetchall()
print(result_set)

When you print it, the output looks like this.

[(4, 'hugh', 'janitorial engineering')]
Series Navigation<< SQLAlchemy Core InsertSQLAlchemy Core Update >>

Leave a Reply