You get a bonus - 1 coin for daily activity. Now you have 1 coin

bash/sh: working with MySQL from the command line or scripts

Practice



The MySQL server can be used not only from applications or websites. You can quite easily send queries and get some kind of output from them right from bash or sh scripts themselves - i.e., from "shell" scripts.

Here's an example of a small file that runs a SELECT query and puts the result into a variable:

#!/bin/sh

res=`mysql -u USERNAME --password=PASSWORD --database=DATABASE --skip-column-names --default-character-set=KOI8-R --batch --execute="SELECT * FROM mytable"`

Here:
  • USERNAME : Substitute the username for this database
  • PASSWORD : The database user's password
  • DATABASE : Which database to use
  • KOI8-R : The encoding. I strongly recommend specifying it explicitly, even if it seems to work without it.
  • --skip-column-names : Don't print column headers
  • --batch : Run in batch mode, which means the output won't contain the pseudo-graphic characters that are normally present to show the table borders.


If you need the output to contain the pseudo-graphic characters - i.e., for example, you're showing the output directly to the user - there's no need to specify the "-batch" flag.

After running, the $res variable will contain the SELECT output result.

By analogy, you can also run other queries, such as UPDATE, DELETE, and everything else.

Applicable to: Any Unix; MySQL 5.x+

Comments

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "Databases - MySql (Maria DB)"

Terms: Databases - MySql (Maria DB)