From the course: Using SQL with Python

Using the module

- [Instructor] It's simple to import and use this module. You'll notice down here on line five, I say from BwDB import, and then our two classes, BwDB, and BWErr. And then I simply use the class. Like I would any other class, here I am initializing an object with the BwDB connected to SQLite, or if I like I can do it connected to SQL. and either one works. Once it's connected, I can use it just as we did in the test code, here I use SQL do to drop a table if exists and here I use SQL do to create a table. Once I've created this temp table, it's named temp, I can set the table name to temp, and then I can use all of the crud methods. So I can say column names, I can use add row with or without the commit. But here since I'm adding a bunch of rows at once, I use no commit and I hit commit down below. I can use get rows as an iterator. I can use find rows to find all the rows that have an S in them. And then I get a list of row IDs, and then I can iterate through the list of row IDs to print them. I can find a particular row with Bird in it. And once I have that row ID, I can update that row and change the name. I can add a row using add row. I can delete a row using find, and then passing that row ID to delete row and I can add a bunch more rows. And then I can page through the rows using limit and offset. I can change the table to a different table and get those rows and I can change it back and just get those rows. Drop table if exists and the close of the database handle and the cursor is handled by the destructor in the class. So I'll just go ahead and run it this, and you'll see all of these things happening here. We create the table. There's the table column names, populate the table, find the rows with an S in them, search just for Bird , change it from Charlie Bird to The Bird . We can add a row. We can delete a row, print the remaining rows. You'll notice there that three, which was Billy Cobham has gone. Add more rows, we have 13 more rows, and then we can page through them five at a time. We change our table and here's our items table, change it back and drop the table. And if we like, I can run that same code against my SQL. And it works exactly the same, little slower because SQLite is all in one compact little file. And this is actually running on a server in my office. So you can see here that this module is easy and convenient to use. And in the next chapter, we'll use it for a practical application.

Contents