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

相关推荐
RacentCLM几秒前
HTTPS只在登录时有用?关于TLS的误解讲清
数据库·网络协议·https
杨云龙UP19 分钟前
生产实战:Keepalived + Nginx + MySQL 双向复制高可用架构部署与原理详解
运维·数据库·mysql·nginx·架构·keepalived·高可用架构
代钦塔拉32 分钟前
【C++/Qt 进阶】设计模式系列(7):过滤器模式——把“筛选条件“变成可组合的积木
数据库·系统架构
threerocks34 分钟前
2026 深度盘点:我评估了 369 个 Claude/CodeX AI 视频与自动化剪辑开源项目
aigc·openai·ai编程
TDengine (老段)1 小时前
TDengine IDMP 十大亮点功能(一)
大数据·数据库·物联网·时序数据库·tdengine·涛思数据
为思念酝酿的痛1 小时前
MySQL的基本查询
数据库·mysql
花间相见1 小时前
【计算基础|Redis01】【上手】安装连接、配置与通用命令
数据库·后端·面试
geovindu1 小时前
Pivoting and Unpivoting Data in SQL using postgreSQL 18
大数据·数据库·数据仓库·sql·postgresql·数据库开发·数据库架构
我命由我123451 小时前
6-3.Python 异常处理 - 异常处理进阶(else 块与 finally 块、异常传递、自定义异常)
开发语言·前端·数据库·后端·python·学习·java-ee