Run a single MySQL query from the command line
Posted November 6th, 2008 in MySql
The MySQL command line utility allows you to run queries and view query results etc from an interactive command prompt. It is also possible to run a single query from the command line without actually going into the interactive prompt. This post looks at how to do this.
As an example, I needed to load some data into a new database the other day from a dump from another server. Normally I'd do something like this:
mysql -u [username] -p somedb < somedb.sql
The database didn't actually exist so I got this error:
ERROR 1049 (42000): Unknown database 'somedb'
The obvious solution is to create the database and then run the same command to load the data. I could either do this by adding the "create database somedb" to the start of the text file I was loading, fire up the MySQL command line, run the command and exit back to the bash shell, or use the -e flag to execute a single query.
So to run a single MySQL query from your regular shell instead of from MySQL's interactive command line you would do this:
mysql -u [username] -p [dbname] -e [query]
In my case I wanted to create the database so it looked like this (note I didn't need to specify a database because my query didn't affect a specific database):
mysql -u [username] -p -e "create database somedb"
You can run any valid queries against any databases you have permissions for, in the same way as running the query from the MySQL command line. Any output will appear on your shell's command line. For example:
$ mysql -u root -p somedb -e "select * from mytable" Enter password: +------------+-------------+----------------------------+ | mytable_id | category_id | name | +------------+-------------+----------------------------+ | 1 | 1 | Lorem ipsum dolor sit amet | | 2 | 1 | Ut purus est | | 3 | 2 | Leo sed condimentum semper | | 4 | 2 | Donec velit neque | | 5 | 3 | Maecenas ullamcorper | +------------+-------------+----------------------------+
Update and insert queries do not output anything if they are successful (displaying errors if not successful), but select queries do as shown in the above example.
Related posts:
- Renaming a table in MySQL (Wednesday, July 2nd 2008)
- Running queries from the MySQL Command Line (Wednesday, April 16th 2008)
- Using the MySQL command line tool (Sunday, April 13th 2008)
- Executing shell commands from within the MySQL command line client (Friday, April 11th 2008)
Share or Bookmark
Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.
Subscribe or Follow
Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.
