问题描述
我正在尝试执行脚本以使用Golang将数据填充到数据库中
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\n: %+v, %v", out.String(), stderr.String(), err))
log.Fatalf("Error executing query. Command Output: %+v\n: %+v, %v", out.String(), stderr.String(), err)
}
}
问题是我遇到了错误:
ERROR 1049 (42000): Unknown database '< /Users/XXX/Documents/test/scripts/olds/SCRIPT_XXX.sql'
我认为问题是执行程序认为是dbname的最后一个参数(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
但是我尝试在Go中复制以自动执行脚本.
but i try to replicate in Go to automatize the execution of the script.
该脚本具有删除表,创建表,插入和具有FK关系的PK,这是一个非常完整的关系,因此我无法一行一行地执行,因此我决定执行de mysql程序以将数据插入数据库中.
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.
有什么建议吗?
推荐答案
+1来回答@MatteoRagni,以演示如何在Golang中执行stdin重定向.
+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")
您不必使mysql客户端使用stdin重定向读取脚本.相反,您可以使mysql客户端执行特定的命令,即 source< scriptname>
.
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 .:我也不会在代码中输入主机,端口,用户和密码.这意味着,只要更改这些连接参数,就必须重新编译程序.同样,在命令行上以纯文本格式使用密码也不安全.相反,我将所有连接参数放入默认文件中,并使用 mysql --defaults-file = FILENAME
.
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
.
这篇关于如何使用exec.Command在Golang中执行Mysql脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!