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 驱动。

相关推荐
Vect__9 小时前
C++无痛转go第一天,从hello world到切片
开发语言·c++·golang
ljz20169 小时前
递归CTE查询优化方案
数据库
IT果果日记9 小时前
人大金仓使用Flink-CDC
大数据·数据库·后端
peterfei9 小时前
IfAI v0.4.6 发布:多线程并发对话 + Rust TUI 架构重构实战
人工智能·ai编程
程序员鱼皮9 小时前
吴恩达新的免费 AI 课来了,YYDS!我已经学上了
计算机·ai·程序员·编程·ai编程
2301_782040459 小时前
JavaScript中Map在频繁增删键值对场景下的稳定性
jvm·数据库·python
a7963lin9 小时前
Golang怎么用GitLab CI构建_Golang如何编写.gitlab-ci.yml自动化构建流程【教程】
jvm·数据库·python
名不经传的养虾人10 小时前
从0到1:企业级AI项目迭代日记 Vol.18|功能被悄悄改没了,然后我们写了个看门狗
大数据·人工智能·ai编程·企业ai·多agent协作
熊文豪10 小时前
国产数据库的中流砥柱:KingbaseES 高可用集群架构深度解析
数据库·架构