douxiong5438 2017-10-23 17:02
浏览 247


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= --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.

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



  • ¥15 js指定时间段显示图片广告
  • ¥15 Pycharm中程序直接运行可以但进入调试报错
  • ¥15 MATLAB动图问题
  • ¥15 有段代码不知道怎么理解,const isToken = (config.headers || {}).isToken === false
  • ¥15 我的显卡支持CUDA最高版本是12.3,这个版本也支持VS 2022 17.0这种情况下如果我想下载CUDA11.8,需要下载旧版本的VS2022吗
  • ¥100 采用栈和深度优先算法取消graphics库采用其他方式显示路径打印显示路径取消graphics库
  • ¥15 pointnet2包安装
  • ¥20 射频功率问题,解答者有酬谢!
  • ¥80 构建降雨和积水的预测模型
  • ¥15 #Qt Transform setTransform()在鼠标拖动移动视角是一致在原地不动,无法变换视角(细微观察似乎视图有在原地抖动),无法变换视角(细微观察似乎视图有在原地抖动)