SQLiteSQLite
טבלאות, SQL בסיסי, sqlite3 ושאילתות בטוחות.
Tables, basic SQL, sqlite3 and safe queries.
טבלת סרטיםA movies table
תזכורת: מה ביקשוReminder: the task
צרו מסד בזיכרון עם טבלה movies (id, title, year), הכניסו שלושה סרטים עם executemany, והדפיסו את כמות הסרטים ואת הכותרות ממוינות לפי שנה.
Create an in-memory database with a movies (id, title, year) table, insert three movies with executemany, and print the count and the titles sorted by year.
הפתרון המלא והפלט שלוFull solution and its output
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE movies (id INTEGER PRIMARY KEY, title TEXT, year INTEGER)")
con.executemany("INSERT INTO movies (title, year) VALUES (?, ?)", [("Up", 2009), ("Coco", 2017), ("Cars", 2006)])
print(con.execute("SELECT COUNT(*) FROM movies").fetchone()[0])
print([r[0] for r in con.execute("SELECT title FROM movies ORDER BY year")])3 ['Cars', 'Up', 'Coco']
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
חיפוש בטוחA safe search
תזכורת: מה ביקשוReminder: the task
בעזרת הטבלה הנתונה, כתבו by_author(con, name) שמחזירה רשימת כותרות של הסופר (חיפוש חלקי, LIKE עם %), ממוינת לפי שנה. השתמשו ב-? בלבד.
Using the given table, write by_author(con, name) returning the author's titles (partial match, LIKE with %), sorted by year. Use ? only.
הפתרון המלא והפלט שלוFull solution and its output
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),
])
def by_author(con, name):
rows = con.execute("SELECT title FROM books WHERE author LIKE ? ORDER BY year", ("%" + name + "%",))
return [r[0] for r in rows]
print(by_author(con, "dahl"))
print(by_author(con, "x' OR '1'='1"))['The BFG', 'Matilda'] []
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
עדכון ומחיקהUpdate and delete
תזכורת: מה ביקשוReminder: the task
כתבו set_pages(con, title, pages) שמעדכנת את מספר העמודים של ספר ומחזירה כמה שורות השתנו, ו-remove(con, title) שמוחקת ספר ומחזירה כמה נמחקו. השתמשו ב-with con:.
Write set_pages(con, title, pages) that updates a book's page count and returns how many rows changed, and remove(con, title) that deletes a book and returns how many were deleted. Use with con:.
הפתרון המלא והפלט שלוFull solution and its output
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),
])
def set_pages(con, title, pages):
with con:
cur = con.execute("UPDATE books SET pages = ? WHERE title = ?", (pages, title))
return cur.rowcount
def remove(con, title):
with con:
cur = con.execute("DELETE FROM books WHERE title = ?", (title,))
return cur.rowcount
print(set_pages(con, "Dune", 604), remove(con, "Emma"), remove(con, "Emma"))
print(con.execute("SELECT title, pages FROM books ORDER BY id").fetchall())1 1 0
[('Dune', 604), ('Matilda', 240), ('The BFG', 208)]יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
סטטיסטיקה ב-SQLStats in SQL
תזכורת: מה ביקשוReminder: the task
כתבו שאילתה אחת שמחזירה לכל סופר: שם, מספר ספרים וממוצע עמודים מעוגל (ROUND(AVG(pages))), ממוינת לפי מספר ספרים מהגבוה ואז לפי שם. החזירו אותה מ-author_stats(con) כרשימת טאפלים.
Write one query returning for each author: name, book count and rounded average pages (ROUND(AVG(pages))), sorted by count descending then by name. Return it from author_stats(con) as a list of tuples.
הפתרון המלא והפלט שלוFull solution and its output
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),
])
def author_stats(con):
q = "SELECT author, COUNT(*), ROUND(AVG(pages)) FROM books GROUP BY author ORDER BY COUNT(*) DESC, author"
return con.execute(q).fetchall()
for row in author_stats(con):
print(row)('Roald Dahl', 2, 224.0)
('Frank Herbert', 1, 412.0)
('Jane Austen', 1, 474.0)יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מדף, צעד 23: המדף עובר למסדShelf, step 23: the shelf moves to a database
תזכורת: מה ביקשוReminder: the task
כתבו מחלקה ShelfDB(path) שמתחברת למסד ויוצרת (IF NOT EXISTS) טבלה books (id, title UNIQUE, author, pages, read DEFAULT 0). מתודות: add(title, author, pages) (מחזירה id), find(text) (חיפוש חלקי בכותרת או בסופר, מחזירה רשימת מילונים), mark_read(title, pages), ו-progress() שמחזירה אחוז כולל מעוגל של עמודים שנקראו. השתמשו ב-con.row_factory = sqlite3.Row כדי לקבל שורות שאפשר להפוך למילון.
Write a class ShelfDB(path) that connects and creates (IF NOT EXISTS) a table books (id, title UNIQUE, author, pages, read DEFAULT 0). Methods: add(title, author, pages) (returns the id), find(text) (partial match on title or author, returns a list of dicts), mark_read(title, pages), and progress() returning the overall rounded percent of pages read. Use con.row_factory = sqlite3.Row to get rows that convert to dicts.
הפתרון המלא והפלט שלוFull solution and its output
import sqlite3
class ShelfDB:
def __init__(self, path):
self.con = sqlite3.connect(path)
self.con.row_factory = sqlite3.Row
with self.con:
self.con.execute("CREATE TABLE IF NOT EXISTS books (id INTEGER PRIMARY KEY, title TEXT UNIQUE NOT NULL, author TEXT, pages INTEGER, read INTEGER DEFAULT 0)")
def add(self, title, author, pages):
with self.con:
cur = self.con.execute("INSERT INTO books (title, author, pages) VALUES (?, ?, ?)", (title, author, pages))
return cur.lastrowid
def find(self, text):
like = f"%{text}%"
rows = self.con.execute("SELECT * FROM books WHERE title LIKE ? OR author LIKE ? ORDER BY title", (like, like))
return [dict(r) for r in rows]
def mark_read(self, title, pages):
with self.con:
self.con.execute("UPDATE books SET read = MIN(pages, read + ?) WHERE title = ?", (pages, title))
def progress(self):
read, total = self.con.execute("SELECT SUM(read), SUM(pages) FROM books").fetchone()
return round(read / total * 100) if total else 0
db = ShelfDB(":memory:")
db.add("Dune", "Frank Herbert", 412)
db.add("Matilda", "Roald Dahl", 240)
db.mark_read("Dune", 300)
db.mark_read("Dune", 300)
print(db.find("dahl"))
print(db.progress())[{'id': 2, 'title': 'Matilda', 'author': 'Roald Dahl', 'pages': 240, 'read': 0}]
63יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
ביקורות ו-JOINReviews and JOIN
תזכורת: מה ביקשוReminder: the task
הוסיפו טבלה reviews (book_id, stars) עם ביקורות, וכתבו top_rated(con, min_reviews=2) שמחזירה טאפלים (title, avg_stars, count) לספרים עם לפחות min_reviews ביקורות, ממוינים לפי ממוצע מהגבוה (ממוצע מעוגל ל-2). השתמשו ב-JOIN, GROUP BY ו-HAVING.
Add a reviews (book_id, stars) table with reviews, and write top_rated(con, min_reviews=2) returning tuples (title, avg_stars, count) for books with at least min_reviews reviews, sorted by average descending (rounded to 2). Use JOIN, GROUP BY and HAVING.
הפתרון המלא והפלט שלוFull solution and its output
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("CREATE TABLE reviews (book_id INTEGER, stars INTEGER)")
con.executemany("INSERT INTO reviews VALUES (?, ?)", [(1, 5), (1, 4), (2, 3), (3, 5), (3, 5), (3, 4), (4, 2)])
def top_rated(con, min_reviews=2):
q = """SELECT b.title, ROUND(AVG(r.stars), 2), COUNT(*)
FROM books b JOIN reviews r ON r.book_id = b.id
GROUP BY b.id HAVING COUNT(*) >= ?
ORDER BY AVG(r.stars) DESC"""
return con.execute(q, (min_reviews,)).fetchall()
print(top_rated(con))
print(top_rated(con, 1)[-1])[('Matilda', 4.67, 3), ('Dune', 4.5, 2)]
('The BFG', 2.0, 1)יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
הגירה מ-JSONMigrating from JSON
תזכורת: מה ביקשוReminder: the task
כתבו migrate(json_text, con) שמקבלת את קובץ ה-JSON של המדף הישן (רשימת מילונים עם title, author, pages ואולי read), יוצרת טבלה אם צריך, ומכניסה הכול בטרנזקציה אחת. ספר בלי title מדולג; כותרת שכבר קיימת לא מוכנסת שוב (INSERT OR IGNORE). מחזירה כמה ספרים נוספו בפועל.
Write migrate(json_text, con) taking the old shelf's JSON (a list of dicts with title, author, pages and maybe read), creating the table if needed, and inserting everything in one transaction. A book without a title is skipped; a title that already exists isn't inserted again (INSERT OR IGNORE). Return how many books were actually added.
הפתרון המלא והפלט שלוFull solution and its output
import json
import sqlite3
def migrate(json_text, con):
books = json.loads(json_text)
before = con.total_changes
with con:
con.execute("CREATE TABLE IF NOT EXISTS books (id INTEGER PRIMARY KEY, title TEXT UNIQUE NOT NULL, author TEXT, pages INTEGER, read INTEGER DEFAULT 0)")
rows = [(b["title"].strip(), b.get("author", ""), b.get("pages", 0), b.get("read", 0)) for b in books if b.get("title", "").strip()]
con.executemany("INSERT OR IGNORE INTO books (title, author, pages, read) VALUES (?, ?, ?, ?)", rows)
return con.total_changes - before
old = '[{"title": "Dune", "author": "Frank Herbert", "pages": 412, "read": 103}, {"title": "Emma", "pages": 474}, {"author": "nobody"}, {"title": "Dune"}]'
con = sqlite3.connect(":memory:")
print(migrate(old, con), migrate(old, con))
print(con.execute("SELECT title, author, read FROM books").fetchall())2 0
[('Dune', 'Frank Herbert', 103), ('Emma', '', 0)]יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.