Executing MySQL Queries Directly From the Command Line

If you are a System Administrator, it will get to some point you only want to run a one line MySQL command. Maybe in some program you are writing or in the console, MySQL/MariaDB Linux package supports that and we are going to run that through.

In this post, I’m using MariaDB, but this works for MySQL too. By the end of this post, you should understand how to run MySQL Queries in one line.

We will be looking at examples of queries from the commandline…

Viewing list of Databases in your System

$ mysql -u root -p -e "SHOW DATABASES;"

To create Databases and start working with them

$ mysql -u root -p -e "CREATE DATABASE unixmen;"

Without output from MySQL, nothing will be returned after running a command like the command above.

Create tables and view tables

$ mysql -u root -p -e "USE unixmen; CREATE TABLE IF NOT EXISTS staffs ( ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR( 200 ) NOT NULL )"
$ mysql -u root -p -e "USE unixmen; SHOW TABLES;"

screenshot_20160927_033016

To Insert into the table

$ mysql -u root -p -e "USE unixmen; INSERT INTO staffs ( name ) VALUES ( 'John' );"

To view data in the table

$ mysql -u root -p -e "USE unixmen; SELECT * FROM staff;

Now we want to output the result to a file, the

tee

command comes in handy or output redirection by running

$ mysql -u root -p -e "USE unixmen; SELECT * FROM staff;" | tee output.txt

The output will be saved to

output.txt

of the working directory. Which can be viewed using

cat

command

$ cat output.txt

screenshot_20160927_034533

Summary

With this, you can set automated tasks as SysAdmins, to make job easier. Linux is just  a flexible OS