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.
Creating a Cursor Object
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.
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.
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
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