简体   繁体   English

如何使用Golang导入/加载/运行mysql文件?

[英]How to import/load/run mysql file using golang?

I'm trying to run/load sql file into mysql database using this golang statement but this is not working: 我正在尝试使用此golang语句将sql文件运行/加载到mysql数据库中,但这不起作用:

exec.Command("mysql", "-u", "{username}", "-p{db password}", "{db name}", "<", file abs path )

But when i use following command in windows command prompt it's working perfect. 但是,当我在Windows命令提示符下使用以下命令时,它的工作正常。

mysql -u {username} -p{db password} {db name} < {file abs path}

So what is the problem? 那是什么问题呢?

As others have answered, you can't use the < redirection operator because exec doesn't use the shell. 正如其他人回答的那样,您不能使用<重定向运算符,因为exec不使用shell。

But you don't have to redirect input to read an SQL file. 但是您不必重定向输入即可读取SQL文件。 You can pass arguments to the MySQL client to use its source command. 您可以将参数传递给MySQL客户端以使用其source命令。

exec.Command("mysql", "-u", "{username}", "-p{db password}", "{db name}",
    "-e", "source {file abs path}" )

The source command is a builtin of the MySQL client. source命令是MySQL客户端的内置命令。 See https://dev.mysql.com/doc/refman/5.7/en/mysql-commands.html 参见https://dev.mysql.com/doc/refman/5.7/en/mysql-commands.html

Go's exec.Command runs the first argument as a program with the rest of the arguments as parameters. Go的exec.Command将第一个参数作为程序运行,其余参数作为参数运行。 The '<' is interpreted as a literal argument. “ <”被解释为文字参数。

eg exec.Command("cat", "<", "abc") is the following command in bash: cat \\< abc . 例如exec.Command("cat", "<", "abc")是bash中的以下命令: cat \\< abc

To do what you want you have got two options. 做您想做的事情,您有两种选择。

The problem with the bash version is that is not portable between different operating systems. bash版本的问题在于它不能在不同的操作系统之间移植。 It won't work on Windows. 在Windows上将无法使用。

Go's os.exec package does not use the shell and does not support redirection: Go的os.exec软件包不使用外壳程序,并且不支持重定向:

Unlike the "system" library call from C and other languages, the os/exec package intentionally does not invoke the system shell and does not expand any glob patterns or handle other expansions, pipelines, or redirections typically done by shells. 与使用C和其他语言进行“系统”库调用不同,os / exec软件包有意不调用系统外壳程序,并且不展开任何glob模式或处理其他通常由外壳程序完成的扩展,管线或重定向。

You can call the shell explicitly to pass arguments to it: 您可以显式调用外壳以将参数传递给它:

cmd := exec.Command("/bin/sh", yourBashCommand)

Depending on what you're doing, it may be helpful to write a short bash script and call it from Go. 根据您的操作,编写简短的bash脚本并从Go调用它可能会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM