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:
mysql -uroot -p -hslavedb.mydomain.com mydb_production "select * from users;"
This question is related to
sql
mysql
unix
command-line
mysql -u <user> -p -e "select * from schema.table"
From the mysql
man page:
You can execute SQL statements in a script file (batch file) like this:
shell> mysql db_name < script.sql > output.tab
Put the query in script.sql
and run it.
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)
echo "select * from users;" | mysql -uroot -p -hslavedb.mydomain.com mydb_production
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
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)
Source: Stackoverflow.com