-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSQLAlchemy_dataclass.py
More file actions
36 lines (29 loc) · 904 Bytes
/
SQLAlchemy_dataclass.py
File metadata and controls
36 lines (29 loc) · 904 Bytes
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
36
from dataclasses import dataclass
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import Session
Base = declarative_base()
@dataclass
class Person(Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
from sqlalchemy import create_engine
engine = create_engine('sqlite:///test.db')
Base.metadata.create_all(bind=engine)
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)
session = Session()
p = Person(name="John", age=30)
session.add(p)
session.commit()
all_persons = session.query(Person).all()
for user in all_persons:
print(user.name, user.age)
p = Person(name="John2222", age=3000)
session.add(p)
session.commit()
all_persons = session.query(Person).all()
for user in all_persons:
print(user.name, user.age)