May 5, 2010

How to execute Mysql query from Linux shell ?

You can run Mysql query directly from Bash shell or KSH shell using "-e or --execute" option of mysql command.


Command: mysql
Options:
-u or --user=name : Mysql User for login if not current user.
-p or --password[=name] : Mysql Password to use when connecting to server.
-e or --execute=name : Execute command and quit.


Syntax:
mysql -u username -p"password" -e "Mysql query"

Examples:
1. This command will execute Mysql query "SELECT * FROM addressbook" directly from the shell prompt.


mysql -u ebuggiuser -p"mypassword" -e "use usersdata; select * from addressbook"

2. SHOW PROCESSLIST - List all Mysql process.

mysql -u ebuggiuser -p"mypassword" -e "SHOW PROCESSLIST"

3. SHOW DATABASES - List all Mysql databases;

mysql -u ebuggiuser -p"mypassword" -e "SHOW DATABASES"

** You can use -s or --silent switch to print Mysql query results in tab separated format.


mysql -u ebuggiuser -p"mypassword" -e "use usersdata; select * from addressbook" -s

No comments: