MySQL 在 docker 容器上执行 SQL 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34779894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 21:31:53  来源:igfitidea点击:

Executing SQL scripts on docker container

mysqldocker

提问by Akron

I have a docker container running mysql and I want to push a .sql file to the container and then have mysql execute the commands in it. The first step is fairly straightforward:

我有一个运行 mysql 的 docker 容器,我想将 .sql 文件推送到容器,然后让 mysql 执行其中的命令。第一步相当简单:

docker cp ./dummy.sql <container_id>:/

From there I am trying to run mysql from the command line and point it to the file that I just pushed to the container.

从那里我试图从命令行运行 mysql 并将其指向我刚刚推送到容器的文件。

docker exec <container_id> mysql -u root -ppassword < /dummy.sql

This command appears to be trying to use /sample.sql as stdin locally rather than on the container. I also tried wrapping quotes around everything after the container ID which also seems to not work.

此命令似乎试图在本地而不是在容器上使用 /sample.sql 作为标准输入。我还尝试在容器 ID 之后的所有内容周围加上引号,这似乎也不起作用。

I also tried pushing a .sh file with the command in it to the docker container and then just executing that, but that is less ideal and also not working. Any advice?

我还尝试将其中包含命令的 .sh 文件推送到 docker 容器,然后执行该文件,但这不太理想,而且也不起作用。有什么建议吗?

采纳答案by Thomasleveil

If you are going to do pipe redirections in your command, pass it as a string to /bin/sh:

如果要在命令中进行管道重定向,请将其作为字符串传递给/bin/sh

docker exec <container_id> /bin/sh -c 'mysql -u root -ppassword </dummy.sql'

回答by PuzzledVacuum

One does not need to copy the script first. After struggling to run my own script I managed to execute it on linux using:

不需要先复制脚本。在努力运行我自己的脚本之后,我设法使用以下命令在 linux 上执行它:

docker exec -it <container_name> mysql -u root -ppassword -e "Use mydb; $(cat /path/to/script.sql)"

docker exec -it <container_name> mysql -u root -ppassword -e "Use mydb; $(cat /path/to/script.sql)"

Or if the Use db directive is contained inside the script:

或者,如果脚本中包含 Use db 指令:

docker exec -it <container_name> mysql -u root -ppassword -e "$(cat /path/to/script.sql)"

docker exec -it <container_name> mysql -u root -ppassword -e "$(cat /path/to/script.sql)"

回答by Andrey

Try:

尝试:

docker exec <container_id> 'mysql -u root -ppassword </dummy.sql'