Advertisement
ksieradzinski

Untitled

Feb 27th, 2025
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.28 KB | None | 0 0
  1. import psycopg2
  2.  
  3.  
  4. def create_tables():
  5.     print("Tworzę tabele...")
  6.     with psycopg2.connect(dbname="books", user="postgres", password="Password!") as connection:
  7.         cursor = connection.cursor()
  8.         cursor.execute("""CREATE TABLE IF NOT EXISTS authors(
  9.            id SERIAL PRIMARY KEY,
  10.            first_name VARCHAR(50) NOT NULL,
  11.            last_name VARCHAR(50) NOT NULL
  12.        )""")
  13.  
  14.         cursor.execute("""CREATE TABLE IF NOT EXISTS books(
  15.                id SERIAL PRIMARY KEY,
  16.                title VARCHAR(50) NOT NULL,
  17.                author_id INTEGER NOT NULL REFERENCES authors(id)
  18.        )""")
  19.  
  20.  
  21. def add_author(author_name: str):
  22.     try:
  23.         first_name, last_name = author_name.split(" ")
  24.         print(f"Dodaję autora {first_name} {last_name}.")
  25.  
  26.         with psycopg2.connect(dbname="books", user="postgres", password="Password!") as connection:
  27.             cursor = connection.cursor()
  28.             cursor.execute(
  29.                 "INSERT INTO authors(first_name, last_name) VALUES(%s,%s)",
  30.                 (
  31.                     first_name,
  32.                     last_name
  33.                 )
  34.             )
  35.             connection.commit()
  36.     except ValueError:
  37.         print("Autor musi posiadać imię i nazwisko np. Henryk Sienkiewicz.")
  38.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement