Mysql Command Line Client: Difference between revisions
Jump to navigation
Jump to search
(10 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
=Internal= | =Internal= | ||
* [[MySQL Operations#Command_Line_Client|MySQL Operations # | * [[MySQL Operations#Command_Line_Client|MySQL Operations | Command Line Client]] | ||
=Options= | |||
==<tt>-e</tt>, <tt>--execute=name</tt>== | |||
Execute command and quit. | |||
==<tt>-D</tt>, <tt>--database=name</tt> | |||
Specify the database to use. | |||
=Connect= | =Connect= | ||
< | <syntaxhighlight lang='bash'> | ||
mysql -u root -p | mysql -u root -p | ||
</ | </syntaxhighlight> | ||
Will challenge for password. | |||
<syntaxhighlight lang='bash'> | |||
mysql -u root -p<password> | |||
</syntaxhighlight> | |||
No space after -p. | |||
The username and password can also be stored in ~/.my.cnf: | |||
<syntaxhighlight lang='text'> | |||
[client] | |||
user = root | |||
password = XXXXXXXX | |||
</syntaxhighlight> | |||
=Scripting Database Interaction= | |||
<syntaxhighlight lang='bash'> | |||
mysql -u root -p<password> < statements.sql | |||
</syntaxhighlight> | |||
where statements.sql should contain SQL: | |||
<syntaxhighlight lang='sql'> | |||
SELECT VERSION(); | |||
... | |||
</syntaxhighlight> | |||
Alternatively: | |||
<syntaxhighlight lang='bash'> | |||
mysql -u root -p<password> -e "SELECT VERSION()" | |||
</syntaxhighlight> | |||
The command sends the result to stdout. If the select query produces no results, the stdout is the empty string: | |||
<syntaxhighlight lang='bash'> | |||
local result | |||
result=$(mysql -u root -p${database_root_password} -e "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='${database_name}'") | |||
if [[ -n ${result} ]]; then | |||
echo "database exists" | |||
else | |||
echo "database does not exist" | |||
fi | |||
</syntaxhighlight> |
Latest revision as of 02:10, 30 December 2023
Internal
Options
-e, --execute=name
Execute command and quit.
==-D, --database=name
Specify the database to use.
Connect
mysql -u root -p
Will challenge for password.
mysql -u root -p<password>
No space after -p.
The username and password can also be stored in ~/.my.cnf:
[client]
user = root
password = XXXXXXXX
Scripting Database Interaction
mysql -u root -p<password> < statements.sql
where statements.sql should contain SQL:
SELECT VERSION();
...
Alternatively:
mysql -u root -p<password> -e "SELECT VERSION()"
The command sends the result to stdout. If the select query produces no results, the stdout is the empty string:
local result
result=$(mysql -u root -p${database_root_password} -e "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='${database_name}'")
if [[ -n ${result} ]]; then
echo "database exists"
else
echo "database does not exist"
fi