How to execute MySQL command from the host to container running MySQL server?

前端 未结 9 1971
春和景丽
春和景丽 2021-01-30 06:31

I have followed the instruction in https://registry.hub.docker.com/_/mysql/ to pull an image and running a container in which it runs a MySQL server.

The container is run

9条回答
  •  感动是毒
    2021-01-30 07:22

    i didn't find any of these solutions to be effective for my use case: needing to store the returned data from the SQL to a bash variable.

    i ended up with the following syntax when making the call from inside a bash script running on the host computer (outside the docker mysql server), basically use 'echo' to forward the SQL statement to stdin on the docker exec command.

    modify the following to specify the mysql container name and proper mysql user and password for your use case:

    #!/bin/bash
    mysqlCMD="docker exec -i _mysql-container-name_ mysql -uroot -proot "
    sqlCMD="select count(*) from DBnames where name = 'sampleDB'"
    count=`echo $sqlCMD | $mysqlCMD | grep -v count`
    
    # count variable now contains the result of the SQL statement
    

    for whatever reason, when i used the -e option, and then provided that string within the back-quotes, the interpreter modified the quotation marks resulting in SQL syntax failure.

    richard

提交回复
热议问题