■ Session 클래스의 add 메소드를 사용해 테이블 행을 추가하는 방법을 보여준다.
▶ 예제 코드 (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 |
from sqlalchemy import func from sqlmodel import SQLModel, Session, JSON, Field, Column, create_engine, select from typing import List class Event(SQLModel, table = True): id : int | None = Field(default = None, primary_key = True) title : str image : str description : str location : str tagList : List[str] = Field(sa_column = Column(JSON)) databaseFilePath = "test.db" databaseURL = f"sqlite:///{databaseFilePath}" connectionArgumentDictionary = {"check_same_thread" : False} engine = create_engine(databaseURL, echo = False, connect_args = connectionArgumentDictionary) SQLModel.metadata.create_all(engine) with Session(engine) as session: sql = select(func.count(Event.id)) # "SELECT count(event.id) AS count_1 FROM event" eventCount = session.scalar(sql) id = eventCount + 1 newEvent = Event(id = id, title = f"제목 {id}", image = f"이미지 {id}", description = f"설명 {id}", location = f"위치 {id}", tagList = [f"테스트 {id}"]) session.add(newEvent) session.commit() session.refresh(newEvent) |