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

Creating a database with SQLite 3

From: Python 3 Essential Training

Video: Creating a database with SQLite 3

There are many database choices available for Python. For our purposes, we're going to be using SQLite3 for a number of reasons. First of all, SQLite3 comes with Python. If you have Python installed and you're watching this course, then you have SQLite3 and that makes it easy for us for the purposes of teaching. SQLite3 is a perfect choice for a lot of applications. For most of the web site work that I do these days, I'm using SQLite3 instead of MySQL which I might have used a few years ago. It's reliable, it's simple, it doesn't require a separate database engine, it's self-contained, server less, zero configuration and fully transactional.

Creating a database with SQLite 3

There are many database choices available for Python. For our purposes, we're going to be using SQLite3 for a number of reasons. First of all, SQLite3 comes with Python. If you have Python installed and you're watching this course, then you have SQLite3 and that makes it easy for us for the purposes of teaching. SQLite3 is a perfect choice for a lot of applications. For most of the web site work that I do these days, I'm using SQLite3 instead of MySQL which I might have used a few years ago. It's reliable, it's simple, it doesn't require a separate database engine, it's self-contained, server less, zero configuration and fully transactional.

It's a fully capable database engine in a driver and that makes it just incredibly easy to use. For our purposes, having something that's simple like this allows me to show you how databases work with Python without having to mess with the database a whole lot and spend our time in the Python. So, I'm going to go ahead and start by making a working copy of databases.py. Call it databases-working.py. Go ahead and load that up. You see our first line here says import sqlite3 and that simply imports the Python Library that supports SQLite3.

And then here all we do is we say db = SQLite3.connect and the name of the file, test.db. And we save this and run it and we have created a database. We'll go ahead and refresh this file system here because Eclipse doesn't do that for us and you see that we now have empty file and we've created our database. So, we'll go ahead and populate the database and that's also very simple. We simply say db.execute and I'm going to give it some SQL here and say drop table if exists so that we can create a new table each time and call the table test.

And then db.execute, create table tees, and give it a couple of fields. t1, it's a text field and i1 is an int and I've created a table inside my database. Now I'll just insert a little bit of data. db.execute insert into test (t1, i1, values (?, ?) and these are placeholders and that allows us to give it a tuple with the values one and 1.

And I'll just make a few of these. Two and give that a 2. And a 3 and a 4. And 4 and a three and we have now inserted some data into our database. So this is all done with SQL and we'll say db.commit() because SQLite is a transactional database. It will buffer these values, in case you're going to be using it in a transactional mode. And then I say cursor = db.execute and select star from test order by t1.

Again, standard SQL for row in cursor: print(row). So, now, I've inserted some data into the database and I'm going to print that data out from the database. Save it and run it and there we have it. There's our four records and they're sorted by the t1 field ,which is our text field, and that's getting read from the database. So, that's all there is to it. Using SQLite in Python is incredibly simple. Our first line here connects to the database and that actually creates the file if the file didn't already exist.

And then, from there on, we're using db.execute because db is the database object that we got back from the connect statement and we simply interact with the database using SQL. Be sure to do a commit after you change any data in the database and then we can do a select and use the cursor object that's returned by db.execute and simply step through the cursor object as an iterator and print the data. The data comes back, you'll notice, in tuples and they're in the order that you specify things in your SQL.

So, if I want it in the i1 first followed by t1, I simply change my SQL so that specifies an order, because the order that was in was the order that we define them in the create table text and then int. So, if I want int and then text, I simply change in my SQL and it'll come back in that order and obviously if I want to order it by the integer instead of by the text, I simply change my SQL and it comes ordered by the integer instead of by the text. There's one more thing I'd like to show you in this context and that is the row factory that comes with SQLite.

The SQLite interface is actually incredibly rich and very full featured in Python and there is a lot of options and a lot of methods that you can override and a tremendous amount of power there for working with databases. We are going to keep it simple for our purposes here but there is one thing that I want to show you and that's what's called a row factory. We'll say db.row_factory = sqlite3.Row.

So, what the row factory does is it allows you to specify how rows will be returned from the cursor and the built-in row factory that's provided, sqlite3.Row, is very powerful and very suitable for most purposes. So, when I save this and run it, you'll notice the only change I made was to add that row factory there after the connect. You'll notice now we get row objects instead of those tuples and the row objects can be looked at as tuples if we'd like or it can be looked at as dictionaries, which I find particularly useful.

So, if I say dictionary like that, I'm creating a dictionary object based on a iterable because row is an iterable. So, if I save this and run it, now I get dictionary objects and so they are completely indexed. If I want to, I can say, rows up t1 and I'll get my t1 objects. I can say row.t1, row.i1 and get all the data. Save that and run it.

The built-in row factory from SQLite is very flexible. I tend to use it in the dictionary mode because I find that very convenient, but it has a lot of other options and they're all documented on the SQLite3 page in the Python documentation. So, as you can see, accessing a database from Python is very simple. Most databases have an interface very similar to this one. For most simple database applications, SQLite3 is going to be a great choice and you can see that it's very simple to use in Python.

Show transcript

This video is part of

Image for Python 3 Essential Training
Python 3 Essential Training

87 video lessons · 42176 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 preferences from 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.

Learn more, save more. Upgrade today!

Get our Annual Premium Membership at our best savings yet.

Upgrade to our Annual Premium Membership today and get even more value from your lynda.com subscription:

“In a way, I feel like you are rooting for me. Like you are really invested in my experience, and want me to get as much out of these courses as possible this is the best place to start on your journey to learning new material.”— Nadine H.

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.