CGO_ENABLED=0 导致 SQLite 驱动初始化失败

执行了go test ./... 以后出现下面的bug

Go 复制代码
?       practic_todolist/cmd/todo       [no test files]
?       practic_todolist/internal/config        [no test files]

2026/04/15 22:44:19 C:/Users/gaoru/Desktop/practic_todolist/internal/handler/todo_handler_test.go:34
[error] failed to initialize database, got error Binary was compiled with 'CGO_ENABLED=0', go-sqlite3 requires cgo to work. This is a stub
--- FAIL: TestTodoHandlerEndpoints (0.01s)
    todo_handler_test.go:55: open test database: Binary was compiled with 'CGO_ENABLED=0', go-sqlite3 requires cgo to work. This is a stub
FAIL
FAIL    practic_todolist/internal/handler       1.211s
?       practic_todolist/internal/model [no test files]
?       practic_todolist/internal/repository    [no test files]
ok      practic_todolist/internal/service       0.596s
?       practic_todolist/pkg/database   [no test files]
FAIL

解决办法:

我的测试代码在连接 SQLite 时失败了,因为当前Go环境是CGO_ENABLED=0,而我现在用的 SQLite 驱动需要CGO。

更直白一点:

项目里的service测试能过,是因为它用了mock仓库,不需要真连数据库,handler集成测试会真的打开 SQLite 内存库,我现在的 SQLite 驱动底层依赖 go-sqlite3,go-sqlite3 在Windows 上通常需要:CGO_ENABLED=1,本机有 C 编译器,但我当前测试是用禁用 CGO 的方式编译出来的,所以数据库初始化直接失败了

报错里这句就是核心:

Binary was compiled with 'CGO_ENABLED=0'

go-sqlite3 requires cgo to work

这意味着目前不是我的业务代码逻辑错了,而是运行环境和SQLite驱动不匹配

有两种解决方案:

第一种是开启 CGO,并安装 C 编译环境

适合继续使用当前 gorm.io/driver/sqlite

先检查

Go 复制代码
go env CGO_ENABLED
gcc --version

如果 CGO_ENABLED 是 0,可以尝试:

Go 复制代码
go env -w CGO_ENABLED=1

但在 Windows 上,通常还要安装 gcc,否则还是不行。

第二种则就是把项目改成"不依赖 CGO"的纯 Go SQLite 驱动。

相关推荐
●VON6 小时前
鸿蒙Flutter实战:分类管理页BottomSheet CRUD
数据库·flutter·华为·harmonyos·鸿蒙
Cosolar6 小时前
Chroma向量库面试学习指南
数据库·人工智能·面试·职场和发展·数据库架构
canonical_entropy7 小时前
Harness Engineering 之外:从非线性动力系统控制理解吸引子引导工程
架构·aigc·ai编程
企服AI产品测评局7 小时前
Agent适配信创环境实测:企业级自动化如何实现国产操作系统与数据库全兼容?
运维·数据库·人工智能·ai·chatgpt·自动化
cfm_29148 小时前
Redis数据安全性解析
数据库·redis·缓存
DIY源码阁8 小时前
JavaSwing学生成绩管理系统 - MySQL版
java·数据库·mysql·eclipse
鹏北海-RemHusband8 小时前
Go 语言进阶笔记 — 面向 JS/TS 前端开发者
笔记·golang
NiceCloud喜云9 小时前
Claude Code Routines 实战:三种触发器跑通云端自动化编码
android·运维·数据库·人工智能·自动化·json·飞书
辞忧九千七9 小时前
Redis 单机一主二从主从复制完整搭建指南
数据库·redis·缓存
lzhdim9 小时前
SQL 入门 16:SQL 事务隔离级别与死锁解析(易懂)
数据库·sql