Skip to content

Latest commit

 

History

History
50 lines (34 loc) · 1.15 KB

3-insertdata.md

File metadata and controls

50 lines (34 loc) · 1.15 KB

<<< Back - Next >>>

Inserting data into an SQL table

Now that we have a table structure, we can insert some data. We need to create a new file for our next steps. Call it insert.py.

The syntax for inserting multiple records is:

INSERT INTO table_name (field_name) VALUES (record1), (record2), (record3);

Insert Anthropology, Biology, and Linguistics into the table we just created. Here is the SQL we need:

INSERT INTO programs (program_name) VALUES
("Anthropology"),
("Biology"),
("Linguistics");

In insert.py, add these lines:

# import sqlite library
import sqlite3

# Make a connection to the 'firstdb.db' database.
conn = sqlite3.connect("firstdb.db")

cursor = conn.cursor()

# insert multiple values into our 'programs' table
cursor.execute("""INSERT INTO programs (program_name) VALUES

('Anthropology'),
('Biology'),
('Linguistics');
""")

conn.commit()

# print out our table
cursor.execute("SELECT * FROM programs")
print(cursor.fetchall())

Run insert.py. If you see the programs we added to the database, it worked!

<<< Back - Next >>>