Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import psycopg2
- def create_tables():
- print("Tworzę tabele...")
- with psycopg2.connect(dbname="books", user="postgres", password="Password!") as connection:
- cursor = connection.cursor()
- cursor.execute("""CREATE TABLE IF NOT EXISTS authors(
- id SERIAL PRIMARY KEY,
- first_name VARCHAR(50) NOT NULL,
- last_name VARCHAR(50) NOT NULL
- )""")
- cursor.execute("""CREATE TABLE IF NOT EXISTS books(
- id SERIAL PRIMARY KEY,
- title VARCHAR(50) NOT NULL,
- author_id INTEGER NOT NULL REFERENCES authors(id)
- )""")
- def add_author(author_name: str):
- try:
- first_name, last_name = author_name.split(" ")
- print(f"Dodaję autora {first_name} {last_name}.")
- with psycopg2.connect(dbname="books", user="postgres", password="Password!") as connection:
- cursor = connection.cursor()
- cursor.execute(
- "INSERT INTO authors(first_name, last_name) VALUES(%s,%s)",
- (
- first_name,
- last_name
- )
- )
- connection.commit()
- except ValueError:
- print("Autor musi posiadać imię i nazwisko np. Henryk Sienkiewicz.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement