Python for the .NET developer 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
0:01 well, of course you want to get it back
0:03 and you want to query it, and slice it, and dice it
0:05 and group it, and all the cool stuff.
0:07 So, here is our function, a simplified version that says
0:10 given a style, a string, we want to get all the guitars
0:13 that have a style that match that string.
0:16 So we're going to go and say create a session.
0:17 Again, bare metal stuff, just SQLAlchemy types
0:20 not our cool, higher level version.
0:23 And we say ctx.session.query(Guitar)
0:26 and then we're going to put the where clause
0:28 basically the filter clause is == style.
0:32 It's really cool how these are called descriptors
0:34 these columns are able to, at run time, be one thing
0:37 and then at, kind of, evaluation time
0:40 like this be yet another.
0:41 So that's a pretty cool language trick and then
0:43 if we were calling list and wrapping it
0:45 we could also do an equivalent thing
0:47 by saying .all and that'll turn into a list.
0:49 Basically, get all the stuff back, and then
0:51 just to be safe, we're wrapping it in a list
0:53 at the bottom here and we're turning that.
0:55 So, this is how we go and query the database.
0:58 We're not doing our order by, but you saw that of course
1:00 if we wanted to, we could order these easily.
1:03 Once we run this query, if we had echo term to true
1:06 which could look at our database tools, you would see that
1:09 we would issue a SQL command over to the database.
1:12 select * from guitars where style = @style.
1:16 Pretty cool, huh? Couple things to note:
1:18 First of all it's using parameters
1:20 so SQL injection attack and little Bobby Tables
1:23 not a problem with SQLAlchemy, which is great.
1:26 The other one is it doesn't technically say
1:28 select . It specifically lists out everything
1:31 that it expects. Get a slightly different
1:33 more complicated-looking output, but
1:35 effectively, there's like a simplified version
1:38 of what happens when we run this code here.