-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsqlalchemy_example.py
35 lines (28 loc) · 1.03 KB
/
sqlalchemy_example.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# set up the database engine and session
engine = create_engine('sqlite:///library.db')
Session = sessionmaker(bind=engine)
session = Session()
# define a base class for declarative class definitions
Base = declarative_base()
# define the Book class
class Book(Base):
__tablename__ = 'books'
id = Column(Integer, primary_key=True, autoincrement=True)
title = Column(String, nullable=False)
author = Column(String, nullable=False)
publication_year = Column(Integer)
# creating the table
Base.metadata.create_all(engine)
# adding a new book
new_book = Book(title='To Kill a Mockingbird', author='Harper Lee', publication_year=1960)
session.add(new_book)
session.commit()
# query and display all books
books = session.query(Book).all()
for book in books:
print(f'{book.id}: {book.title} by {book.author}, {book.publication_year}')
# close the session
session.close()