Python for .NET Developers Transcripts
Chapter: Database access and ORMs in Python
Lecture: Concept: Querying data

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Once you have some data in the database well, of course you want to get it back and you want to query it, and slice it, and dice it
0:06 and group it, and all the cool stuff. So, here is our function, a simplified version that says given a style, a string, we want to get all the guitars
0:14 that have a style that match that string. So we're going to go and say create a session. Again, bare metal stuff, just SQLAlchemy types
0:21 not our cool, higher level version. And we say ctx.session.query(Guitar) and then we're going to put the where clause
0:29 basically the filter clause is guitar.style == style. It's really cool how these are called descriptors
0:35 these columns are able to, at run time, be one thing and then at, kind of, evaluation time like this be yet another.
0:42 So that's a pretty cool language trick and then if we were calling list and wrapping it we could also do an equivalent thing
0:48 by saying .all and that'll turn into a list. Basically, get all the stuff back, and then just to be safe, we're wrapping it in a list
0:54 at the bottom here and we're turning that. So, this is how we go and query the database. We're not doing our order by, but you saw that of course
1:01 if we wanted to, we could order these easily. Once we run this query, if we had echo term to true
1:07 which could look at our database tools, you would see that we would issue a SQL command over to the database.
1:13 select * from guitars where style = @style. Pretty cool, huh? Couple things to note: First of all it's using parameters
1:21 so SQL injection attack and little Bobby Tables not a problem with SQLAlchemy, which is great. The other one is it doesn't technically say
1:29 select . It specifically lists out everything that it expects. Get a slightly different more complicated-looking output, but
1:36 effectively, there's like a simplified version of what happens when we run this code here.


Talk Python's Mastodon Michael Kennedy's Mastodon