execute ( "INSERT INTO fish VALUES ('Jamie', 'cuttlefish', 7)" ) execute ( "INSERT INTO fish VALUES ('Sammy', 'shark', 1)" )Ĭursor. Now that we have created a table, we can insert rows of data into it: cursor. " string is a SQL statement that creates a table named fish with the three columns described earlier: name of type TEXT, species of type TEXT, and tank_number of type INTEGER. Cursor objects allow us to send SQL statements to a SQLite database using cursor.execute(). execute ( "CREATE TABLE fish (name TEXT, species TEXT, tank_number INTEGER)" )Ĭonnection.cursor() returns a Cursor object. We can create this fish table in SQLite using the connection we made in Step 1: cursor = connection. Two example fish rows are listed: one row for a shark named Sammy, and one row for a cuttlefish named Jamie. The fish table will track a value for name, species, and tank_number for each fish at the aquarium. If we run this Python code, we will see output like: We can verify we successfully created our connection object by running: print (connection. The aquarium.db file is created automatically by nnect() if aquarium.db does not already exist on our computer. The nnect() function returns a Connection object that we will use to interact with the SQLite database held in the file aquarium.db. Import sqlite3 gives our Python program access to the sqlite3 module. We can connect to a SQLite database using the Python sqlite3 module: import sqlite3Ĭonnection = sqlite3. For now, we’ll consider a database that tracks the inventory of fish at a fictional aquarium. SQLite databases are fully featured SQL engines that can be used for many purposes. When we connect to a SQLite database, we are accessing data that ultimately resides in a file on our computer. Step 1 - Creating a Connection to a SQLite Database You can review these tutorials for the necessary background information: To get the most out of this tutorial, it is recommended to have some familiarity with programming in Python and some basic background with SQL. We’ll create a connection to a SQLite database, add a table to that database, insert data into that table, and read and modify data in that table.įor this tutorial, we’ll be working primarily with an inventory of fish that we need to modify as fish are added to or removed from a fictional aquarium. In this tutorial, we’ll go through the sqlite3 module in Python 3. SQLite comes bundled with Python and can be used in any of your Python applications without having to install any additional software. SQLite is a self-contained, file-based SQL database. The author selected the COVID-19 Relief Fund to receive a donation as part of the Write for DOnations program.
0 Comments
Leave a Reply. |