bigywater.tech
Flask · 99

SQLite 与 PostgreSQL 行为差异

开发用 SQLite、线上用 PostgreSQL,会踩哪些坑?这篇用同一份代码在两个数据库上并排运行,把五类常见差异逐项打印出来。

5 类
实测的差异:类型、时区、约束与匹配、自增、并发写
database is locked
SQLite 上第二个写者在 0.5 秒超时后的报错
0 行 vs 1 行
LIKE 'hel%' 匹配 'Hello' 时 PostgreSQL 与 SQLite 的结果

类型与长度

实测 · 本机执行输出
  往 INTEGER 列写字符串 "abc"
    sqlite      成功,库里 n = 'abc'
    postgresql  DataError: invalid input syntax for type integer: "abc"
  往 String(5) 列写 10 个字符
    sqlite      成功,存进去的是 'abcdefghij'
    postgresql  DataError: value too long for type character varying(5)

上一篇:数据迁移回滚;下一篇:数据库连接断开后的恢复。

Numeric 与时区

实测 · 本机执行输出
  Numeric(8,2) 存 Decimal("0.30")
    sqlite      读回 Decimal('0.30')(Decimal)
    postgresql  读回 Decimal('0.30')(Decimal)
  DateTime(timezone=True) 存带时区的时间
    sqlite      存入 12:00+08:00,读回 datetime.datetime(2026, 1, 1, 12, 0)
    postgresql  存入 12:00+08:00,读回 datetime.datetime(2026, 1, 1, 12, 0, tzinfo=zoneinfo.ZoneInfo(key='Asia/Shanghai'))

外键与 LIKE

实测 · 本机执行输出
  插入指向不存在父行的子行(外键违反)
    sqlite      成功(外键指向不存在的父行也写进去了)
    postgresql  IntegrityError: insert or update on table "child" violates foreign key constraint "child_pid_fke
  WHERE s LIKE 'hel%'(数据是 'Hello')
    sqlite      LIKE 'hel%' 匹配 'Hello' 的行数 = 1
    postgresql  LIKE 'hel%' 匹配 'Hello' 的行数 = 0

SQLite 的外键默认不强制;是否能用 PRAGMA foreign_keys=ON 打开,本篇没有验证。

自增主键

实测 · 本机执行输出
  主键复用
    sqlite      先插入得到 [1, 2],删掉 2 再插入得到 2
    postgresql  先插入得到 [1, 2],删掉 2 再插入得到 3

并发写

实测 · 本机执行输出
  sqlite      第二个连接写入(第一个持有未提交的写事务 1 秒):OperationalError: database is locked,等了 561 ms
  postgresql  第二个连接写入(第一个持有未提交的写事务 1 秒):ok,等了 10 ms

分步演示

SQLite 与 PostgreSQL
本步的对象

    本文用到的工具与边界

    • 本机 macOS 27 arm64 / Python 3.14.7 / Flask 3.1.3 / Werkzeug 3.1.9 / Jinja2 3.1.6 / SQLAlchemy 2.1.1 / gunicorn 26.2.0(都装在自己的虚拟环境里);大多数实验用 Flask 的 test_client(直接调用 WSGI 应用,不经过网络),需要真实 HTTP 时另起 gunicorn 或开发服务器(端口 9600 以上,本机 127.0.0.1);计时用 time.perf_counter,数字每次运行会有小幅抖动。SQLite(Python 内置 sqlite3)、自己起的 PostgreSQL(非默认端口,会话时区 Asia/Shanghai)
    • 没有验证:PRAGMA foreign_keys=ON 的效果、SQLite 的 WAL 模式对并发写的改善、MySQL 的行为、JSON 与数组类型、全文搜索、事务隔离级别的差异、SQLite 在多进程 gunicorn 下的表现
    京ICP备2026067502号-1京公网安备11010502063487号