SQLite basics in Python
Create, insert, and query with the built-in sqlite3.
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute(
"CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT, year INTEGER)")
conn.execute("INSERT INTO books(title, year) VALUES(?, ?)",
("Dune", 1965))
conn.executemany(
"INSERT INTO books(title, year) VALUES(?, ?)",
[("Neuromancer", 1984), ("Foundation", 1951)])
conn.commit()
rows = conn.execute("SELECT title FROM books WHERE year > ?",
(1960,)).fetchall()
conn.close()
How it works
connect(':memory:')opens a throwaway database.?placeholders bind values safely.executemanyinserts many rows at once.
The run, in numbers
- Lines
- 16
- Characters to type
- 436
- Tokens
- 91
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 52 seconds.
Step 1 of 3 in Databases, step 14 of 41 in Domain tools.