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

相关推荐
穿过生命散发芬芳5 小时前
现在CC Switch一开,Claude Code随便玩
ai编程
yuanyxh8 小时前
macOS 应用 - 纯对话生成
前端·macos·ai编程
倔强的石头_9 小时前
《Kingbase护城河》——数据库存储空间全景探测与精细化瘦身实战
数据库
葫芦和十三9 小时前
多模态融合|是数据形态工程,不是 Prompt 工程
openai·agent·ai编程
码哥字节10 小时前
同事做 PPT 比你快 5 倍,不是因为他努力,是因为他用了这套工具流
ai编程
云技纵横10 小时前
唯一索引 INSERT 死锁实战:5 秒复现交叉插入的 S 锁循环等待
sql·mysql
沉默王二10 小时前
面试官:RAG 不用向量数据库,用 MySQL 硬扛?我:100 万向量不是很轻松?
mysql·面试·ai编程
程序员老刘10 小时前
跨平台开发地图 | 2026年6月
flutter·ai编程·客户端
唐老板10 小时前
给 Claude 定规则:让它写出的代码像我们团队的人写的
ai编程
Avan_菜菜18 小时前
AI 能写代码了,为什么我反而开始要求它先写文档?
前端·github·ai编程