doushi8186 2019-03-26 15:05
浏览 157
已采纳

使用exec.Command运行sqlite3 .backup

I'm attempting to back up a db from Go using the sqlite3 .backup command in the manner give by this SO answer https://stackoverflow.com/a/25684912/426853.

The following always works from the command line:

sqlite3 /home/pi/pgclogs/smartlog.db ".backup '/home/pi/pgcdata/smartlog.db.bak'"

I've coded it in Go as follows:

func DbBackup() (err error) {
    dbpath := "/home/pi/pgclogs/smartlog.db"
    bakpath := "/home/pi/pgcdata/smartlog.db.bak"
    cmd := exec.Command("sqlite3", dbpath, fmt.Sprintf("\".backup '%s'\"", bakpath))
    out, err := cmd.CombinedOutput()
    if err != nil {
        return fmt.Errorf("dbBackup failed : %s : %v", string(out), err)
    }
    return
} 

and I have a test file that invokes it like this:

func TestDbBackup(t *testing.T) {
    var err error
    err = DbBackup()
    if err != nil {
        t.Errorf("backup failed : %v", err)
    }
} 

The test reports a syntax error from sqlite3.

--- FAIL: TestDbBackup (0.01s)
    db_backup_test.go:22: backup failed : dbBackup failed : Error: near "".backup '/home/pi/pgcdata/smartlog.db.bak'"": syntax error
         : exit status 1

I suspect the problem is the way cmd.CombinedOutput is passing the arguments to the shell and that the problem is in the quoting in the fmt.Sprintf call. I've tried changing it to

fmt.Sprintf(`".backup '%s'"`, bakpath)

but the result is the same. I also tried putting echo in front of the command, i.e exec.Command("echo", "sqlite3", dbpath, ... and printing the output. The output looks absolutely correct

sqlite3 /home/pi/pgclogs/smartlog.db ".backup '/home/pi/pgcdata/smartlog.db.bak'"

and it runs correctly when pasted to the command line. I'm sure I'm overlooking something simple, but I've spent over an hour and am still not seeing it.

  • 写回答

1条回答 默认 最新

  • dtpngq3378499 2019-03-26 16:11
    关注

    You don't need the additional quotes at all, so this should do:

    exec.Command("sqlite3", dbpath, fmt.Sprintf(".backup '%s'", bakpath))
    

    The quotes are parsed by the shell so that .backup 'somefile' gets passed to sqlite3 as a single argument. When using exec.Command, there is no shell involved, that's also the reason why you are passing the command splitted into multiple parameters.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥66 如何制作支付宝扫码跳转到发红包界面
  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题