Start learning with our library of video tutorials taught by experts. Get started
Viewers: in countries Watching now:
Due to its power, simplicity, and complete object model, Python has become the scripting language of choice for many large organizations, including Google, Yahoo, and IBM. In Python 3 Essential Training, Bill Weinman demonstrates how to use Python 3 to create well-designed scripts and maintain existing projects. This course covers the basics of the language syntax and usage, as well as advanced features such as objects, generators, and exceptions. Example projects include a normalized database interface and a complete working CRUD application. Exercise files accompany the course.
When you are writing an application that uses a database, sometimes it's a good idea to create a class that handles that particular schema. Let's take a look at an example of how you can do that in Python. We'll start by making a working copy of sqlite3-class.py, and we will call it sqlite3-class-working.py, and we'll go ahead and open up that working copy. And here we have a complete working example of a class. It's very simple. It's just a few lines of code, and how we access that class through this interface.
We'll go ahead and run it and you can see what it does. This is just an example of testing this particular class, so it creates a table test and it creates some rows and retrieves the rows. It tests these four functions of the database. So if we look at our interface, we create our object by passing in a file name and a table name, and that will actually initialize the database. And then we create the table using some sql. Then we insert some rows using dictionary objects.
Then we retrieve rows, just using keys, and it will retrieve dictionary objects. And retrieve test, there is our dictionary objects. We update a couple of rows, again, using dictionary objects, and there they are. These dictionary objects could instead be specific classes that you've created for your database application. And we delete rows with keys. And you'll notice that every time we do one of these operations, we're printing out all the rows in a database using the database handle itself as an iterator.
So this is a nice little convenient interface. First of all, the constructor takes these two arguments as named arguments using the kwargs pattern. And the first one is the filename and it assigns it to a filename property. And the second one is the table and it assigns it to a table property. And you'll notice that these do not have underscores, because these are meant to be accessible to the outside world. Down here, I use the property decorator to allow the filename to be assigned like that, and when it gets assigned it actually connects to the database and it sets up the row_factory.
And when you delete the file name, it actually closes the database. And so this allows you to use this kind of a pattern for assigning the filename, and you can even do this on the object level, using the object, and it will go ahead and initialize the database like that. Likewise, with the table, it sets the table name and that one is just really simply setting this _table variable, and if you delete it, it defaults to test, so that there is always a table name. Because it will kind of break the code here if there isn't a table name, if the table name is blank, and you'll see that as we go through.
So the insert function is very simple, and you'll notice it goes off the end of the screen here. So I'll just go ahead and reformat that. So the sql, insert into it, and you'll notice that we have to use a replacement in the string using format, because the question mark pattern doesn't work for the table name. That's true across the board in every database entry that I have ever used. If you want to use the positional parameters, you cannot do that for the table name, and so I allow the table name to be set using the format here and it uses the underscore table.
And then, the row is passed in as a dictionary object and here we make a tuple out of the two parameters that we are inserting, the values t1 and i1, and they are positional like that in order. So insert looks like that. Retrieve looks like this. It returns a dictionary object using the fetch 1 method of the database cursor and the sql is just a simple select * from the table name. We are replacing the table name using format and we are using positional arguments over here for the key, and again, this is single element tuple and so it has to have that comma. Because the comma is what creates the tuple, not the parenthesis.
Update, it takes a row as a dictionary object and it passes the menu using that tuple, and the same pattern here. We're replacing the table name using the string format method, and delete uses a key and there is the single element tuple there, and all of these methods that change the database, they all have this db.commit. There is a display rows method that we are not actually using, which does what we were doing in our other examples. It simply prints them out using a print function.
But here is how we are looking at the data in this example. We are using this iter method. That's a special method in Python. If you put this in your class, it allows your object to be used as an iterator. So it has two underscores __iter__ for its name, and other than that, it works just like any method. And it's a generator because it uses yield, and this allows it to operate as an iterator. So it simply yields a dictionary of the row, and that allows us to call it like this, for row in db:print(row), and we get these results.
So we'll go ahead and we'll save this and we'll run it again, and we see there we have our results. Finally, it's worth noting that because of this pattern down here at the bottom, if __name__="__main__": main(), this entire file will work just fine as a module in Python. You could simply say import sqlite3-class-working and you would have access to this class and be able to use this in another file.
And this main function down here will be completely ignored, because when you import it that way, this is no longer true and so main will not be called. So it's a useful pattern to be able to write a module like this and to have a class that you are going to use throughout a project or even to distribute it to the world. And to test it using a main function that is really just there for testing purposes. So this is a useful pattern and it's one that you'll probably use.
Here we have a custom class for working with a specific database, and a lot of different techniques that you can use in building a class like that for yourself. It does the major four functions and it does a couple of other things. The object itself is useable as an iterator, because we included an iterator method. It uses properties for setting the filename that make it easy to change files if you want to. So here we have an example of how you can create a custom class for your own database schema, for your own project, using Python's object-oriented features to make your programming task a lot easier.
Find answers to the most frequently asked questions about Python 3 Essential Training.
Here are the FAQs that matched your search "":
Sorry, there are no matches for your search ""—to search again, type in another word or phrase and click search.
Access exercise files from a button right under the course name.
Search within course videos and transcripts, and jump right to the results.
Remove icons showing you already watched videos if you want to start over.
Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.
Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.