How do you run a single query through mysql from the command line?

前端 未结 5 1924
旧巷少年郎
旧巷少年郎 2021-01-30 08:02

I\'m looking to be able to run a single query on a remote server in a scripted task.

For example, intuitively, I would imagine it would go something like:



        
相关标签:
5条回答
  • 2021-01-30 08:19

    here's how you can do it with a cool shell trick:

    mysql -uroot -p -hslavedb.mydomain.com mydb_production <<< 'select * from users'
    

    '<<<' instructs the shell to take whatever follows it as stdin, similar to piping from echo.

    use the -t flag to enable table-format output

    0 讨论(0)
  • 2021-01-30 08:24

    If it's a query you run often, you can store it in a file. Then any time you want to run it:

    mysql < thefile
    

    (with all the login and database flags of course)

    0 讨论(0)
  • 2021-01-30 08:26
    mysql -u <user> -p -e "select * from schema.table"
    
    0 讨论(0)
  • 2021-01-30 08:30
    echo "select * from users;" | mysql -uroot -p -hslavedb.mydomain.com mydb_production
    
    0 讨论(0)
  • 2021-01-30 08:32
    mysql -uroot -p -hslavedb.mydomain.com mydb_production -e "select * from users;"
    

    From the usage printout:

    -e, --execute=name
    Execute command and quit. (Disables --force and history file)

    0 讨论(0)
提交回复
热议问题