חלקPart 4: נתונים ורשתData & the web
כ-3 שעות (כולל הפסקה)About 3 hours (with a break)
SQLiteSQLite
טבלאות, SQL בסיסי, sqlite3 ושאילתות בטוחות.
Tables, basic SQL, sqlite3 and safe queries.
הנקודות החשובותKey points
- JSON טוב לקצת נתוניםJSON is fine for a little data
- מסד: חיפוש מהיר, עדכון של שורה אחתA database: fast search, update one row
CREATE TABLEעם עמודות וטיפוסיםCREATE TABLEwith columns and types- `id INTEGER PRIMARY KEY` גדל לבד`id INTEGER PRIMARY KEY` grows by itself
WHEREמסנן,ORDER BYממיין,LIMITחותךWHEREfilters,ORDER BYsorts,LIMITtrimsLIKE '%dahl%'לחיפוש חלקיLIKE '%dahl%'for partial search- לעולם לא f-string בתוך SQLNever an f-string inside SQL
?+ טאפל ערכים?+ a tuple of valuesUPDATE ... SET ... WHEREUPDATE ... SET ... WHERE
מונחיםTerms
- מסד נתוניםdatabase: מקום מסודר לשמירת הרבה נתונים, עם שפה לשאילתות. SQLite שומר את כל המסד בקובץ אחד.An organised store for lots of data, with a query language. SQLite keeps the whole database in one file.
- טבלהtable: אוסף רשומות עם אותן עמודות, כמו גיליון: שורה לכל ספר, עמודה לכל שדה.A collection of records with the same columns, like a sheet: one row per book, one column per field.
- SQLSQL: השפה לשאול ולשנות מסדי נתונים:
SELECT title FROM books WHERE pages > 300.The language for asking and changing databases:SELECT title FROM books WHERE pages > 300. - מפתח ראשיprimary key: עמודה שמזהה כל שורה באופן ייחודי, בדרך כלל
idשגדל לבד.A column that uniquely identifies each row, usually anidthat grows by itself. - סימן ? (placeholder)placeholder:
?בשאילתה שבמקומו SQLite מכניס ערך בבטחה. מונע SQL injection.A?in a query where SQLite safely inserts a value. Prevents SQL injection. - SQL injectionSQL injection: פרצה שבה קלט של משתמש שמודבק לשאילתה משנה את משמעותה. נמנעת עם
?.A hole where user input pasted into a query changes its meaning. Prevented with?. - commit (במסד)commit (database): שמירה סופית של שינויים במסד. בלי
con.commit()(אוwith con:), השינויים הולכים לאיבוד.Making changes permanent in the database. Withoutcon.commit()(orwith con:), changes are lost. - JOINJOIN: חיבור שתי טבלאות לפי עמודה משותפת, למשל ספרים וביקורות לפי book_id.Combining two tables by a shared column, e.g. books and reviews by book_id.
Cheatsheet
למהWhy
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)CREATECREATE
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),SELECTSELECT
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),??
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),שינוייםChanges
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)")GROUP BYGROUP BY
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),שגיאות שפגשנוErrors we met
| שגיאהError | מה זה אומרWhat it means | מה עושיםWhat to do |
|---|---|---|
sqlite3.IntegrityError | מכניסים שורה בלי ערך לעמודה שהיא NOT NULL.Inserting a row without a value for a NOT NULL column. | sqlite3.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. |
sqlite3.OperationalError | יוצרים טבלה שכבר קיימת (למשל בהרצה שנייה).Creating a table that already exists (e.g. on a second run). | sqlite3.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. |
sqlite3.OperationalError | שם עמודה עם שגיאת כתיב.A column name with a typo. | sqlite3.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. |
sqlite3.ProgrammingError | שוכחים את הפסיק בטאפל של ערך יחיד.Forgetting the comma in a one-value tuple. | 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",). |
AssertionError | UPDATE בלי WHERE משנה את כל הטבלה.UPDATE without WHERE changes the whole table. | AssertionError: 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 = ?. |
AssertionError | בוחרים עמודה שאינה בקיבוץ ומצפים לרשימה.Selecting a non-grouped column and expecting a list. | AssertionError: 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). |