-1

I’m trying to run/load sql file into mysql database using this golang statement but this is not working:

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.

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

So what is the problem?

3
  • try exec.Command("C\", "mysql", "-u", "{username}", "-p{db password}", "{db name}", "<", file abs path ).Run() Commented Mar 15, 2018 at 14:52
  • "C\" - what does this string stand for? Commented Mar 15, 2018 at 14:55
  • it runs cmd from the C drive if i remember correctly, for it solved my problems Commented Mar 15, 2018 at 15:21

3 Answers 3

5

As others have answered, you can't use the < redirection operator because exec doesn't use the shell.

But you don't have to redirect input to read an SQL file. You can pass arguments to the MySQL client to use its source command.

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. See https://dev.mysql.com/doc/refman/5.7/en/mysql-commands.html

Sign up to request clarification or add additional context in comments.

Comments

1

Go's exec.Command runs the first argument as a program with the rest of the arguments as parameters. The '<' is interpreted as a literal argument.

e.g. exec.Command("cat", "<", "abc") is the following command in 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. It won't work on Windows.

Comments

1

Go's os.exec package does not use the shell and does not support redirection:

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.

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.

2 Comments

I'm a windows user.
Ah yes, then bash isn't a good fit for you. I assume there's some modern, useful shell command you can invoke - or shell script file you can run - in Windows, but I'm not a Windows expert. Mysql's source (above) is likely the easiest solution for your issue. Hopefully you still found the excerpt from the package documentation informative.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.