SQLiteSQLite
טבלאות, SQL בסיסי, sqlite3 ושאילתות בטוחות.
Tables, basic SQL, sqlite3 and safe queries.
01למה מסד נתונים?Why a database?
קובץ JSON טוב למדף של 20 ספרים. אבל עם 20,000, כל חיפוש דורש לטעון הכול, וכל שינוי דורש לכתוב הכול מחדש. מסד נתונים שומר טבלאות ויודע לחפש, למיין ולעדכן שורה אחת ביעילות. SQLite מגיע עם פייתון, בלי התקנה, ושומר הכול בקובץ אחד.
A JSON file is fine for a 20-book shelf. But with 20,000, every search means loading everything, and every change means rewriting it all. A database stores tables and searches, sorts and updates a single row efficiently. SQLite comes with Python, nothing to install, and keeps everything in one file.
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT NOT NULL, pages INTEGER)")
con.execute("INSERT INTO books (title, pages) VALUES ('Dune', 412)")
for row in con.execute("SELECT * FROM books"):
print(row)
print(sqlite3.sqlite_version)(1, 'Dune', 412) 3.53.1
JSON הוא כמו מחברת: נוח לרשימה קצרה. מסד נתונים הוא כמו קטלוג בספרייה עירונית: עם אינדקס, מגירות ומספרים, כדי למצוא ספר אחד מתוך מאה אלף בשנייה.
JSON is like a notebook: handy for a short list. A database is like a city library's catalogue: indexes, drawers and numbers, to find one book among a hundred thousand in a second.
מכניסים שורה בלי ערך לעמודה שהיא NOT NULL.
Inserting a row without a value for a NOT NULL column.
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT NOT NULL)")
con.execute("INSERT INTO books (title) VALUES (NULL)")Traceback (most recent call last):
File "/Users/you/python-course/first_db.py", line 4, in <module>
con.execute("INSERT INTO books (title) VALUES (NULL)")
~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
sqlite3.IntegrityError: NOT NULL constraint failed: books.titlesqlite3.IntegrityError: NOT NULL constraint failed: books.title: המסד שומר על הכללים שהגדרנו. ספר חייב כותרת.sqlite3.IntegrityError: NOT NULL constraint failed: books.title: the database enforces the rules we defined. A book must have a title.02טבלה ושורותTables and rows
SQL היא שפה נפרדת שכותבים בתוך מחרוזות. CREATE TABLE מגדיר עמודות: TEXT, INTEGER, REAL. המפתח הראשי id מקבל מספר חדש בכל הכנסה. executemany מכניס רשימה שלמה בבת אחת. מוסכמה: מילות SQL באותיות גדולות, כדי להבדיל אותן מהשמות שלנו.
SQL is a separate language written inside strings. CREATE TABLE defines columns: TEXT, INTEGER, REAL. The primary key id gets a fresh number on each insert. executemany inserts a whole list at once. Convention: SQL keywords in capitals, to tell them apart from our names.
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT NOT NULL, author TEXT, pages INTEGER, year INTEGER)")
con.executemany("INSERT INTO books (title, author, pages, year) VALUES (?, ?, ?, ?)", [
("Dune", "Frank Herbert", 412, 1965), ("Emma", "Jane Austen", 474, 1815),
("Matilda", "Roald Dahl", 240, 1988), ("The BFG", "Roald Dahl", 208, 1982),
])
print(con.execute("SELECT COUNT(*) FROM books").fetchone())
print(con.execute("SELECT id, title FROM books").fetchall())(4,) [(1, 'Dune'), (2, 'Emma'), (3, 'Matilda'), (4, 'The BFG')]
CREATE TABLE הוא כמו לשרטט את הכותרות של טבלה במחברת לפני שממלאים: מחליטים פעם אחת מה העמודות, וכל שורה מתאימה להן.
CREATE TABLE is like ruling the headings of a table in a notebook before filling it: decide the columns once, and every row fits them.
יוצרים טבלה שכבר קיימת (למשל בהרצה שנייה).
Creating a table that already exists (e.g. on a second run).
import sqlite3
con = sqlite3.connect(":memory:")
for run in range(2):
con.execute("CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT)")Traceback (most recent call last):
File "/Users/you/python-course/create.py", line 4, in <module>
con.execute("CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT)")
~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
sqlite3.OperationalError: table books already existssqlite3.OperationalError: table books already exists: כותבים CREATE TABLE IF NOT EXISTS books (...), וכך אפשר להריץ שוב ושוב.sqlite3.OperationalError: table books already exists: write CREATE TABLE IF NOT EXISTS books (...), and you can run it again and again.03SELECT: לשאולSELECT: asking
SELECT הוא הלב של SQL: אילו עמודות, מאיזו טבלה, ואילו שורות. WHERE הוא כמו if, ORDER BY הוא כמו sorted, ו-LIMIT הוא כמו חיתוך. LIKE עם % מחפש חלק ממחרוזת (בלי רגישות לאותיות באנגלית).
SELECT is the heart of SQL: which columns, from which table, and which rows. WHERE is like if, ORDER BY is like sorted, and LIMIT is like slicing. LIKE with % searches part of a string (case-insensitive for English).
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT NOT NULL, author TEXT, pages INTEGER, year INTEGER)")
con.executemany("INSERT INTO books (title, author, pages, year) VALUES (?, ?, ?, ?)", [
("Dune", "Frank Herbert", 412, 1965), ("Emma", "Jane Austen", 474, 1815),
("Matilda", "Roald Dahl", 240, 1988), ("The BFG", "Roald Dahl", 208, 1982),
])
for row in con.execute("SELECT title, pages FROM books WHERE pages > 300 ORDER BY pages DESC"):
print(row)
print(con.execute("SELECT title FROM books WHERE author LIKE '%dahl%' ORDER BY year").fetchall())
print(con.execute("SELECT title FROM books ORDER BY year LIMIT 1").fetchone())('Emma', 474)
('Dune', 412)
[('The BFG',), ('Matilda',)]
('Emma',)SELECT הוא כמו לבקש מספרן: "תביא לי רק כותרות ועמודים, רק של ספרים מעל 300 עמודים, מהעבה לדקה".
SELECT is like asking a librarian: "bring me only titles and pages, only books over 300 pages, thickest first".
שם עמודה עם שגיאת כתיב.
A column name with a typo.
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT NOT NULL, author TEXT, pages INTEGER, year INTEGER)")
con.executemany("INSERT INTO books (title, author, pages, year) VALUES (?, ?, ?, ?)", [
("Dune", "Frank Herbert", 412, 1965), ("Emma", "Jane Austen", 474, 1815),
("Matilda", "Roald Dahl", 240, 1988), ("The BFG", "Roald Dahl", 208, 1982),
])
con.execute("SELECT titel FROM books")Traceback (most recent call last):
File "/Users/you/python-course/select.py", line 9, in <module>
con.execute("SELECT titel FROM books")
~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^
sqlite3.OperationalError: no such column: titelsqlite3.OperationalError: no such column: titel: SQLite אומר בדיוק מה לא מצא. בודקים את השם מול ה-CREATE TABLE.sqlite3.OperationalError: no such column: titel: SQLite says exactly what it didn't find. Check the name against CREATE TABLE.לפני SQL, אותו רעיון ברשימה: בוחרים שורות לפי תנאי.
Before SQL, the same idea on a list: pick rows by a condition.
rows = [("Noa", 15), ("Dan", 11), ("Lia", 17)]
teens = [name for name, age in rows if age >= 13]
print(teens)
print(sorted(rows, key=lambda r: r[1]))['Noa', 'Lia']
[('Dan', 11), ('Noa', 15), ('Lia', 17)]צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
04? בטוח מול injectionSafe ? and injection
כשערך מגיע מהמשתמש, מכניסים אותו עם `?` וטאפל של ערכים, ו-SQLite מטפל בו כנתון בלבד. אם מדביקים קלט עם f-string, קלט זדוני יכול לשנות את השאילתה עצמה: זה SQL injection, אחת הפרצות הנפוצות בעולם. בדוגמה, אותו קלט משפיע אחרת לגמרי בשתי הדרכים:
When a value comes from the user, insert it with `?` and a tuple of values, and SQLite treats it purely as data. If you paste input with an f-string, malicious input can change the query itself: that's SQL injection, one of the world's most common holes. In the example, the same input behaves completely differently in the two ways:
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT NOT NULL, author TEXT, pages INTEGER, year INTEGER)")
con.executemany("INSERT INTO books (title, author, pages, year) VALUES (?, ?, ?, ?)", [
("Dune", "Frank Herbert", 412, 1965), ("Emma", "Jane Austen", 474, 1815),
("Matilda", "Roald Dahl", 240, 1988), ("The BFG", "Roald Dahl", 208, 1982),
])
evil = "x' OR '1'='1"
unsafe = con.execute(f"SELECT title FROM books WHERE author = '{evil}'").fetchall()
safe = con.execute("SELECT title FROM books WHERE author = ?", (evil,)).fetchall()
print("unsafe:", len(unsafe), "rows")
print("safe:", len(safe), "rows")unsafe: 4 rows safe: 0 rows
? הוא כמו טופס עם שדות נעולים: מה שכותבים בשדה "שם" נשאר שם, ולא יכול פתאום להפוך להוראה לפקיד.
? is like a form with locked fields: whatever is written in the "name" box stays a name and can't suddenly become an instruction to the clerk.
שוכחים את הפסיק בטאפל של ערך יחיד.
Forgetting the comma in a one-value tuple.
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT NOT NULL, author TEXT, pages INTEGER, year INTEGER)")
con.executemany("INSERT INTO books (title, author, pages, year) VALUES (?, ?, ?, ?)", [
("Dune", "Frank Herbert", 412, 1965), ("Emma", "Jane Austen", 474, 1815),
("Matilda", "Roald Dahl", 240, 1988), ("The BFG", "Roald Dahl", 208, 1982),
])
con.execute("SELECT * FROM books WHERE title = ?", ("Dune"))Traceback (most recent call last):
File "/Users/you/python-course/inject.py", line 9, in <module>
con.execute("SELECT * FROM books WHERE title = ?", ("Dune"))
~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 4 supplied.sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 4 supplied.: ("Dune") הוא מחרוזת, ופייתון ספרה 4 אותיות. טאפל של ערך אחד: ("Dune",).sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 4 supplied.: ("Dune") is a string, so Python counted 4 letters. A one-value tuple: ("Dune",).05UPDATE, DELETE ו-commitUPDATE, DELETE and commit
UPDATE משנה שורות קיימות, DELETE מוחק. תמיד עם WHERE: בלעדיו, השינוי חל על כל הטבלה. במסד בקובץ, שינויים נשמרים רק אחרי commit. הדרך הנוחה: בלוק with con:, שעושה commit בסוף (ומבטל הכול אם הייתה שגיאה). cur.rowcount אומר כמה שורות הושפעו.
UPDATE changes existing rows, DELETE removes them. Always with WHERE: without it, the change hits the whole table. In a file database, changes are saved only after a commit. The handy way: a with con: block, which commits at the end (and undoes everything if there was an error). cur.rowcount says how many rows were affected.
import sqlite3
from pathlib import Path
Path("shelf.db").unlink(missing_ok=True)
con = sqlite3.connect("shelf.db")
with con:
con.execute("CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT, read INTEGER DEFAULT 0)")
con.executemany("INSERT INTO books (title) VALUES (?)", [("Dune",), ("Emma",), ("Matilda",)])
with con:
cur = con.execute("UPDATE books SET read = 1 WHERE title = ?", ("Dune",))
print("updated:", cur.rowcount)
cur = con.execute("DELETE FROM books WHERE title = ?", ("Emma",))
print("deleted:", cur.rowcount)
con.close()
con = sqlite3.connect("shelf.db")
print(con.execute("SELECT title, read FROM books").fetchall())updated: 1
deleted: 1
[('Dune', 1), ('Matilda', 0)]commit הוא כמו ללחוץ "שלח" על מייל: אפשר לכתוב ולמחוק כמה שרוצים, אבל רק השליחה הופכת את זה לסופי.
commit is like pressing "send" on an email: you can type and delete all you like, but only sending makes it final.
UPDATE בלי WHERE משנה את כל הטבלה.
UPDATE without WHERE changes the whole table.
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT NOT NULL, author TEXT, pages INTEGER, year INTEGER)")
con.executemany("INSERT INTO books (title, author, pages, year) VALUES (?, ?, ?, ?)", [
("Dune", "Frank Herbert", 412, 1965), ("Emma", "Jane Austen", 474, 1815),
("Matilda", "Roald Dahl", 240, 1988), ("The BFG", "Roald Dahl", 208, 1982),
])
con.execute("UPDATE books SET pages = 0")
left = con.execute("SELECT COUNT(*) FROM books WHERE pages > 0").fetchone()[0]
assert left == 3, f"meant to zero one book, but {4 - left} books now have 0 pages"Traceback (most recent call last):
File "/Users/you/python-course/update.py", line 11, in <module>
assert left == 3, f"meant to zero one book, but {4 - left} books now have 0 pages"
^^^^^^^^^
AssertionError: meant to zero one book, but 4 books now have 0 pagesAssertionError: meant to zero one book, but 4 books now have 0 pages: בלי WHERE, כל השורות מתעדכנות. כותבים WHERE id = ?.AssertionError: meant to zero one book, but 4 books now have 0 pages: without WHERE, every row is updated. Write WHERE id = ?.06קיבוץ וחיבור טבלאותGrouping and joining
SQL יודע לסכם: COUNT(*) סופר, AVG(pages) ממוצע. GROUP BY author נותן שורה אחת לכל סופר. וכשיש שתי טבלאות, ספרים וביקורות, JOIN מחבר אותן לפי עמודה משותפת (reviews.book_id = books.id), כך שכל ביקורת מופיעה עם כותרת הספר שלה.
SQL can summarise: COUNT(*) counts, AVG(pages) averages. GROUP BY author gives one row per author. And with two tables, books and reviews, JOIN connects them by a shared column (reviews.book_id = books.id), so each review appears with its book's title.
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT NOT NULL, author TEXT, pages INTEGER, year INTEGER)")
con.executemany("INSERT INTO books (title, author, pages, year) VALUES (?, ?, ?, ?)", [
("Dune", "Frank Herbert", 412, 1965), ("Emma", "Jane Austen", 474, 1815),
("Matilda", "Roald Dahl", 240, 1988), ("The BFG", "Roald Dahl", 208, 1982),
])
for row in con.execute("SELECT author, COUNT(*), SUM(pages) FROM books GROUP BY author ORDER BY COUNT(*) DESC, author"):
print(row)
con.execute("CREATE TABLE reviews (book_id INTEGER, stars INTEGER)")
con.executemany("INSERT INTO reviews VALUES (?, ?)", [(1, 5), (1, 4), (3, 5)])
q = "SELECT books.title, AVG(reviews.stars) FROM books JOIN reviews ON reviews.book_id = books.id GROUP BY books.id"
print(con.execute(q).fetchall())('Roald Dahl', 2, 448)
('Frank Herbert', 1, 412)
('Jane Austen', 1, 474)
[('Dune', 4.5), ('Matilda', 5.0)]GROUP BY הוא כמו למיין כביסה לערימות לפי צבע ואז לספור כל ערימה. JOIN הוא כמו להצמיד לכל גרב את בן הזוג שלה לפי הדוגמה.
GROUP BY is like sorting laundry into piles by colour then counting each pile. JOIN is like pairing each sock with its partner by pattern.
בוחרים עמודה שאינה בקיבוץ ומצפים לרשימה.
Selecting a non-grouped column and expecting a list.
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT NOT NULL, author TEXT, pages INTEGER, year INTEGER)")
con.executemany("INSERT INTO books (title, author, pages, year) VALUES (?, ?, ?, ?)", [
("Dune", "Frank Herbert", 412, 1965), ("Emma", "Jane Austen", 474, 1815),
("Matilda", "Roald Dahl", 240, 1988), ("The BFG", "Roald Dahl", 208, 1982),
])
rows = con.execute("SELECT author, title FROM books GROUP BY author").fetchall()
assert len(rows) == 4, f"got {len(rows)} rows: GROUP BY collapses each author to one row"Traceback (most recent call last):
File "/Users/you/python-course/group.py", line 10, in <module>
assert len(rows) == 4, f"got {len(rows)} rows: GROUP BY collapses each author to one row"
^^^^^^^^^^^^^^
AssertionError: got 3 rows: GROUP BY collapses each author to one rowAssertionError: got 3 rows: GROUP BY collapses each author to one row: אחרי קיבוץ, כל קבוצה היא שורה אחת. לרשימת כותרות לכל סופר: GROUP_CONCAT(title).AssertionError: got 3 rows: GROUP BY collapses each author to one row: after grouping each group is one row. For a list of titles per author: GROUP_CONCAT(title).סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.