开发用 SQLite、线上用 PostgreSQL,会踩哪些坑?这篇用同一份代码在两个数据库上并排运行,把五类常见差异逐项打印出来。
往 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(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')) 插入指向不存在父行的子行(外键违反)
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' 的行数 = 0SQLite 的外键默认不强制;是否能用 PRAGMA foreign_keys=ON 打开,本篇没有验证。
主键复用
sqlite 先插入得到 [1, 2],删掉 2 再插入得到 2
postgresql 先插入得到 [1, 2],删掉 2 再插入得到 3sqlite 第二个连接写入(第一个持有未提交的写事务 1 秒):OperationalError: database is locked,等了 561 ms postgresql 第二个连接写入(第一个持有未提交的写事务 1 秒):ok,等了 10 ms