douxiong5438 2017-10-23 17:02
浏览 248
已采纳

如何使用exec.Command在Golang中执行Mysql脚本

Hi i am trying to execute a script to fill data into a database using Golang

func executeTestScript(){
    cmd := exec.Command("/usr/local/mysql/bin/mysql", "-h127.0.0.1", "-P3333", "-uusr", "-pPassxxx", "-Ddtb_test",  "< /Users/XXX/Documents/test/scripts/olds/SCRIPT_XXX.sql")

    var out, stderr bytes.Buffer

    cmd.Stdout = &out
    cmd.Stderr = &stderr

    err := cmd.Run()
    if err != nil {
        fmt.Println(fmt.Sprintf("Error executing query. Command Output: %+v
: %+v, %v", out.String(), stderr.String(), err))
        log.Fatalf("Error executing query. Command Output: %+v
: %+v, %v", out.String(), stderr.String(), err)
    }
}

The problem is that i am getting the error:

ERROR 1049 (42000): Unknown database '< /Users/XXX/Documents/test/scripts/olds/SCRIPT_XXX.sql'

i think the problem is the last param (the sql script path) that the exec thinks is the dbname

The following command in the terminal is working:

/usr/local/mysql/bin/mysql --host=127.0.0.1 --port=3333 --user=usr --password=Passxxx --database=dtb_test < /Users/XXX/Documents/roseula/scripts/olds/SCRIPT_XXX.sql

but i try to replicate in Go to automatize the execution of the script.

The script have drop tables, create tables, inserts, and PK with FK relationships its a very complete one so i cant execute line by line, because of that i decided to execute de mysql program to insert the data in the database.

Any suggestions?

  • 写回答

2条回答 默认 最新

  • dongziya9863 2017-10-23 17:23
    关注

    +1 to answer from @MatteoRagni for showing how to do stdin redirection in Golang.

    But here's a simple alternative that I use:

    cmd := exec.Command("/usr/local/mysql/bin/mysql", "-h127.0.0.1", "-P3333", 
      "-uusr", "-pPassxxx", "-Ddtb_test",
      "-e", "source /Users/XXX/Documents/test/scripts/olds/SCRIPT_XXX.sql")
    

    You don't have to make the mysql client read the script using stdin redirection. Instead, you can make the mysql client execute a specific command, which is source <scriptname>.

    P.S.: I also would not put the host, port, user, and password in your code. That means you have to recompile your program any time you change those connection parameters. Also it's not secure to use passwords in plaintext on the command-line. Instead, I'd put all the connection parameters into a defaults file and use mysql --defaults-file=FILENAME.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 怎么在stm32门禁成品上增加记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B
  • ¥15 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 解riccati方程组