Inspect Database Return Types
00:00 In this lesson, I want to sidetrack a little bit just to continue establishing this connection in your brain between lists and database records. I told you before that lists are kind of like read-only database records, and it’s by no accident that a lot of Python libraries that allow you to interact with databases can return the rows of a database as tuples.
Here’s a script that creates a database named
"company_db" and with a table
employees. And then just inserts values into this. And you can see down here the tuple that we’re inserting is, again, the one that you’ve seen before with employee ID, a name, and then a role.
Basically, I’ll go ahead and press F5 to run this code. And you can see that the database
company_db was created successfully. So now I should have this sitting in my documents folder and now I’ll be able to open a different file,
and I’m connecting to this database and then selecting everything that’s in the
employees table. And then just fetch the first row. There’s only one row in there, and that’ll be returned as a tuple.
02:18 And as you can see, this is in fact a tuple. So Python represents the data that it gets back from the database, this one record, as a tuple. And then you can also see here that we unpacked them successfully.
03:03 Here’s a quick write-up of the code that I used to create this database, and then also to read from the database. And as I mentioned, you’ll find this code also in the downloadable resources if you’re curious to look at it some more.
Become a Member to join the conversation.