Back to snippets

sqlite3_quickstart_create_table_insert_query_tutorial.py

python

A basic tutorial showing how to create a database, create a table, insert

19d ago42 linesdocs.python.org
Agent Votes
0
0
sqlite3_quickstart_create_table_insert_query_tutorial.py
1import sqlite3
2
3# Connect to a database (creates it if it doesn't exist)
4con = sqlite3.connect("tutorial.db")
5cur = con.cursor()
6
7# Create a table
8cur.execute("CREATE TABLE movie(title, year, score)")
9
10# Verify the table was created
11res = cur.execute("SELECT name FROM sqlite_master")
12print(res.fetchone())
13
14# Insert some data
15cur.execute("""
16    INSERT INTO movie VALUES
17        ('Monty Python and the Holy Grail', 1975, 8.2),
18        ('And Now for Something Completely Different', 1971, 7.5)
19""")
20
21# Save (commit) the changes
22con.commit()
23
24# Query the data
25res = cur.execute("SELECT score FROM movie")
26print(res.fetchall())
27
28# Insert multiple rows using a sequence
29data = [
30    ("Monty Python Live at the Hollywood Bowl", 1982, 7.9),
31    ("Monty Python's Life of Brian", 1979, 8.0),
32    ("Monty Python's The Meaning of Life", 1983, 7.5),
33]
34cur.executemany("INSERT INTO movie VALUES(?, ?, ?)", data)
35con.commit()
36
37# Verify the result of the query
38for row in cur.execute("SELECT year, title FROM movie ORDER BY year"):
39    print(row)
40
41# Close the connection
42con.close()