SqlAlchemy

Leonhardt 2022-04-06 Python
  • Python
  • Database
About 1 min

# 基本用法

# 创建表

import os
from datetime import datetime

from sqlalchemy import Column, DateTime, Integer, String, create_engine
from sqlalchemy.orm import declarative_base, sessionmaker

BASE_DIR = os.path.dirname(os.path.realpath(__file__))
connection_str = 'sqlite:///' + os.path.join(BASE_DIR, 'user.db')

Base = declarative_base() # 声明table
Session = sessionmaker() # 用于管理事物
engine = create_engine(connection_str, echo=True) # 连接数据库, echo=True表示将使用的sql语句打印出来。

# TABLE
class User(Base):
    __tablename__ = 'users' # 表名
    id = Column(Integer(), primary_key=True)
    username = Column(String(5), nullable=False, unique=True)
    email = Column(String(80), nullable=False, unique=True)
    date_created = Column(DateTime(), default=datetime.utcnow)

    def __repr__(self) -> str:
        return f'User(id={self.id}, username={self.username}, email={self.email}, date_created={self.date_created})'

Base.metadata.create_all(engine) # 如果有table声明了但没创建,则创建它
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

# 增删改查