You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go项目中如何访问子目录下的SQLite数据库文件?

解决Go+Gorm访问子目录SQLite数据库的问题

问题原因

你使用sqlite.Open("/simulator/data/gorm.sqlite")时,开头的/代表系统根目录,而非你的项目根目录,程序会去系统根路径下查找文件,自然找不到目标数据库。

解决方案

方案1:使用项目根目录相对路径

因为你运行程序时的工作目录是项目根(能正常访问根目录的gorm.sqlite),直接去掉路径开头的斜杠即可:

sqlite.Open("simulator/data/gorm.sqlite")

方案2:使用当前文件相对路径

你的router.go位于simulator目录下,相对于该文件,数据库的路径是data/gorm.sqlite:

sqlite.Open("data/gorm.sqlite")

方案3:动态生成绝对路径(最可靠)

如果担心运行程序时工作目录变化导致路径失效,可以通过代码动态获取路径并拼接:

import (
    "gorm.io/driver/sqlite"
    "gorm.io/gorm"
    "os"
    "path/filepath"
)

func SetupConfig() {
    config := &driver.Config{}
    // 获取项目根目录(当前工作目录)
    rootDir, err := os.Getwd()
    if err != nil {
        panic(err)
    }
    // 拼接数据库绝对路径
    dbPath := filepath.Join(rootDir, "simulator", "data", "gorm.sqlite")
    if db, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{}); err != nil {
        panic(err)
    } else {
        config.Db = db
    }
    // 其他代码
}

也可以通过runtime.Caller获取当前文件所在目录来拼接:

import (
    "gorm.io/driver/sqlite"
    "gorm.io/gorm"
    "path/filepath"
    "runtime"
)

func SetupConfig() {
    config := &driver.Config{}
    // 获取当前文件的绝对路径
    _, filename, _, ok := runtime.Caller(0)
    if !ok {
        panic("无法获取当前文件路径")
    }
    // 获取当前文件所在的simulator目录
    currentDir := filepath.Dir(filename)
    // 拼接数据库路径
    dbPath := filepath.Join(currentDir, "data", "gorm.sqlite")
    if db, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{}); err != nil {
        panic(err)
    } else {
        config.Db = db
    }
    // 其他代码
}

内容的提问来源于stack exchange,提问作者Sami Al-Subhi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 14:30:24