Learn

Once we have sqlite3 imported, we will need to connect to a database. We can connect to a new or pre-existing database with the sqlite3.connect() API. Remember that an Application Programmable Interface (API) is simply a way to communicate between different applications. In this case, we want Python and SQLite to communicate with one another. This call will connect to the database with the given name. If the database does not exist, it will create new blank database.

# Create connection to database connection = sqlite3.connect("first.db")

We can imagine our connection object as a cable that connects our python environment to our SQLite database.

This is a gif that shows a two-sided arrow pointing between a box labeled "Python" and a box labeled "SQLite." Above this two-sided arrow is a label that says "sqlite3.connect()" symbolizing the idea that our connection object acts as a cable that connects our python environment to our SQLite database.

Creating a Cursor Object

With sqlite3.connect() we have established a connection to the SQLite database “first.db”. Next, we need a way to call SQL statements on the data within the database. To do this, we use something called a cursor object. Using a cursor object, we can:

  • represent a database cursor
  • call statements to our SQLite database
  • return the data in our python environment. We create a cursor object by using the cursor method from the connection class:
    # Create cursor object cursor = connection.cursor()

If we imagine the connection object as a cable that connects Python to SQLite, the cursor uses the cable to move back and forth to send messages and exchange data between the two.

This is a gif that is similar to the previous one above. It shows a box labeled "Python" and a box labeled "SQLite" connected by a yellow rectangle labeled "connection." A small pink box labeled "cursor" continuously travels between the "Python" box and the "SQLite" box through the "connection" rectangle to simulate the idea the cursor uses the connection object to move back and forth to send messages and exchange data between our Python environment and SQLite environment.

Titanic Dataset

For this lesson, you will be using the titanic.db database file that contains data for each real Titanic passenger. To your right, you will see a web browser that displays the data description for each field in titanic.db.

Instructions

1.

We have imported the sqlite3 module for you.

Create a connection object with sqlite3.connect(), and name this object con. Be sure to use the database "titanic.db".

2.

Now that you are connected to the "titanic.db" database, create a cursor object with .cursor() and name it curs. Be sure to attach the connection object that you just created to .cursor().

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?