2.1 KiB
		
	
	
	
	
	
	
	
			
		
		
	
	- 
Import from sqlmodeleverything we will use, including the newselect()function.
- 
Create the Heroclass model, representing theherotable.
- 
Create the engine, we should use a single one shared by all the application code, and that's what we are doing here. 
- 
Create all the tables for the models registered in SQLModel.metadata.This also creates the database if it doesn't exist already. 
- 
Create each one of the Heroobjects.You might not have this in your version if you had already created the data in the database. 
- 
Create a new session and use it to addthe heroes to the database, and thencommitthe changes.
- 
Create a new session to query data. /// tip Notice that this is a new session independent from the one in the other function above. But it still uses the same engine. We still have one engine for the whole application. /// 
- 
Use the select()function to create a statement selecting all theHeroobjects.This selects all the rows in the herotable.
- 
Use session.exec(statement)to make the session use the engine to execute the internal SQL statement.This will go to the database, execute that SQL, and get the results back. It returns a special iterable object that we put in the variable results.This generates the output: INFO Engine BEGIN (implicit) INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age FROM hero INFO Engine [no key 0.00032s] ()
- 
Iterate for each Heroobject in theresults.
- 
Print each hero.The 3 iterations in the forloop will generate this output:id=1 name='Deadpond' age=None secret_name='Dive Wilson' id=2 name='Spider-Boy' age=None secret_name='Pedro Parqueador' id=3 name='Rusty-Man' age=48 secret_name='Tommy Sharp'
- 
At this point, after the withblock, the session is closed.This generates the output: INFO Engine ROLLBACK
- 
Add this function select_heroes()to themain()function so that it is called when we run this program from the command line.
