大家好,伦敦凌晨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)
}
最佳答案
使用这个(单独的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)
}
}