Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Creating a database object

From: Python 3 Essential Training

Video: Creating a database object

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.

Creating a database object

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.

Show transcript

This video is part of

Image for Python 3 Essential Training
Python 3 Essential Training

87 video lessons · 38635 viewers

Bill Weinman
Author

 
Expand all | Collapse all
  1. 5m 14s
    1. Welcome
      1m 32s
    2. Understanding prerequisites for Python
      2m 4s
    3. Using the exercise files
      1m 38s
  2. 33m 29s
    1. Getting started with "Hello World"
      4m 43s
    2. Selecting code with conditionals
      4m 45s
    3. Repeating code with a loop
      4m 13s
    4. Reusing code with a function
      2m 43s
    5. Creating sequences with generator functions
      2m 46s
    6. Reusing code and data with a class
      4m 39s
    7. Greater reusability with inheritance and polymorphism
      7m 17s
    8. Handling errors with exceptions
      2m 23s
  3. 22m 32s
    1. Installing Python 3 and Eclipse for Windows
      11m 24s
    2. Installing Python 3 and Eclipse for Mac
      11m 8s
  4. 28m 0s
    1. Creating a main script
      3m 27s
    2. Understanding whitespace in Python
      4m 8s
    3. Commenting code
      3m 28s
    4. Assigning values
      3m 37s
    5. Selecting code and values with conditionals
      4m 46s
    6. Creating and using functions
      3m 54s
    7. Creating and using objects
      4m 40s
  5. 31m 23s
    1. Understanding variables and objects in Python
      2m 46s
    2. Distinguishing mutable and immutable objects
      2m 41s
    3. Using numbers
      3m 34s
    4. Using strings
      6m 38s
    5. Aggregating values with lists and tuples
      4m 55s
    6. Creating associative lists with dictionaries
      4m 24s
    7. Finding the type and identity of a variable
      4m 45s
    8. Specifying logical values with True and False
      1m 40s
  6. 9m 42s
    1. Selecting code with if and else conditional statements
      2m 22s
    2. Setting multiple choices with elif
      2m 14s
    3. Understanding other strategies for multiple choices
      2m 38s
    4. Using the conditional expression
      2m 28s
  7. 11m 26s
    1. Creating loops with while
      1m 27s
    2. Iterating with for
      3m 54s
    3. Enumerating iterators
      3m 22s
    4. Controlling loop flow with break, continue, and else
      2m 43s
  8. 23m 28s
    1. Performing simple arithmetic
      2m 14s
    2. Operating on bitwise values
      3m 30s
    3. Comparing values
      3m 32s
    4. Operating on Boolean values
      2m 59s
    5. Operating on parts of a container with the slice operator
      6m 52s
    6. Understanding operator precedence
      4m 21s
  9. 11m 34s
    1. Using the re module
      1m 4s
    2. Searching with regular expressions
      3m 12s
    3. Replacing with regular expressions
      3m 29s
    4. Reusing regular expressions with re.compile
      3m 49s
  10. 9m 10s
    1. Learning how exceptions work
      1m 18s
    2. Handling exceptions
      4m 15s
    3. Raising exceptions
      3m 37s
  11. 23m 1s
    1. Defining functions
      6m 23s
    2. Using lists of arguments
      2m 26s
    3. Using named function arguments
      4m 32s
    4. Returning values from functions
      1m 55s
    5. Creating a sequence with a generator function
      7m 45s
  12. 47m 29s
    1. Understanding classes and objects
      5m 12s
    2. Using methods
      6m 12s
    3. Using object data
      10m 4s
    4. Understanding inheritance
      5m 11s
    5. Applying polymorphism to classes
      7m 13s
    6. Using generators
      9m 48s
    7. Using decorators
      3m 49s
  13. 18m 54s
    1. Understanding strings as objects
      3m 25s
    2. Working with common string methods
      5m 24s
    3. Formatting strings with str.format
      5m 31s
    4. Splitting and joining strings
      2m 49s
    5. Finding and using standard string methods
      1m 45s
  14. 25m 27s
    1. Creating sequences with tuples and lists
      4m 6s
    2. Operating on sequences with built-in methods
      5m 50s
    3. Organizing data with dictionaries
      4m 56s
    4. Operating on character data with bytes and byte arrays
      10m 35s
  15. 11m 46s
    1. Opening files
      2m 4s
    2. Reading and writing text files
      4m 33s
    3. Reading and writing binary files
      5m 9s
  16. 21m 27s
    1. Creating a database with SQLite 3
      6m 56s
    2. Creating, retrieving, updating, and deleting records
      7m 31s
    3. Creating a database object
      7m 0s
  17. 18m 27s
    1. Using standard library modules
      8m 0s
    2. Finding third-party modules
      5m 47s
    3. Creating a module
      4m 40s
  18. 23m 11s
    1. Dealing with syntax errors
      8m 19s
    2. Dealing with runtime errors
      4m 0s
    3. Dealing with logical errors
      4m 22s
    4. Using unit tests
      6m 30s
  19. 19m 56s
    1. Normalizing a database interface
      6m 39s
    2. Deconstructing a database application
      8m 9s
    3. Displaying random entries from a database
      5m 8s
  20. 29s
    1. Goodbye
      29s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Python 3 Essential Training.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

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.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.