【问题标题】:os/exec to dump mysql data to fileos/exec 将 mysql 数据转储到文件
【发布时间】:2016-07-10 01:59:43
【问题描述】:

大家好,伦敦快凌晨 3 点了,我输了这场战斗。我正在尝试将 mysql 数据库转储到 sql 文件中。它在命令行中可以正常工作,但当我尝试从 Go 中执行相同操作时(使用 os/exec 库)就不行了。我几乎尝试了我愚蠢的头脑所能想到的一切......它与 echo 命令一起工作正常,但它完全忽略了 mysqldump。你能指出我正确的方向吗?

package main

import (
    "os/exec"
    "log"
    "bufio"
    "os"
    "io"
)

func main() {
    // This Doesn't
    // cmd := exec.Command("mysqldump", "-P3306 -hhost -uuser -ppassword database_name")
    // This Works
    cmd := exec.Command("echo", "Hello World bla bla")
    stdout, err := cmd.StdoutPipe()
    if err != nil {
        log.Fatal(err)
    }

    outfile, err := os.Create("./out.sql")
    if err != nil {
        log.Fatal(err)
    }
    defer outfile.Close()

    // start the command after having set up the pipe
    if err := cmd.Start(); err != nil {
        log.Fatal(err)
    }

    // read command's stdout line by line
    in := bufio.NewWriter(outfile)
    defer in.Flush()

    io.Copy(outfile, stdout)
}

【问题讨论】:

    标签: go


    【解决方案1】:

    使用这个(单独的 Args):

    cmd := exec.Command("mysqldump", "-P3306", "-hhost", "-uuser", "-ppassword", "database_name")
    

    我的测试示例代码:

    package main
    
    import (
        "io/ioutil"
        "log"
        "os/exec"
    )
    
    func main() {
        cmd := exec.Command("mysqldump", "-P3306", "-hhost", "-uuser", "-ppassword", "database_name")
        stdout, err := cmd.StdoutPipe()
        if err != nil {
            log.Fatal(err)
        }
    
        if err := cmd.Start(); err != nil {
            log.Fatal(err)
        }
    
        bytes, err := ioutil.ReadAll(stdout)
        if err != nil {
            log.Fatal(err)
        }
        err = ioutil.WriteFile("./out.sql", bytes, 0644)
        if err != nil {
            panic(err)
        }
    
    }
    

    【讨论】:

    • 如何压缩它?
    【解决方案2】:

    cmd := exec.Command("mysqldump", "-P3306", "-hhost", "-uuser", "-ppassword", "database_name" "table_name") 只需添加表名 w

    【讨论】:

    • 您好,看起来答案不完整 - 请通过完成来修复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-06
    • 1970-01-01
    • 2016-02-19
    • 2013-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多