| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
mysql, The Command-line Tool
| 8.2.1 How to Run SQL Commands from a Text File |
mysql is a simple SQL shell (with GNU readline capabilities).
It supports interactive and non-interactive use. When used interactively,
query results are presented in an ASCII-table format. When used
non-interactively (for example, as a filter), the result is presented in
tab-separated format. (The output format can be changed using command-line
options.) You can run scripts simply like this:
shell> mysql database < script.sql > output.tab |
If you have problems due to insufficient memory in the client, use the
--quick option! This forces mysql to use
mysql_use_result() rather than mysql_store_result() to
retrieve the result set.
Using mysql is very easy. Just start it as follows:
mysql database or mysql --user=user_name --password=your_password
database. Type an SQL statement, end it with `;', `\g', or `\G'
and press Enter.
mysql supports the following options:
-?, --help
-A, --no-auto-rehash
--prompt=...
-b, --no-beep
-B, --batch
--character-sets-dir=...
-C, --compress
-#, --debug[=...]
-D, --database=...
--default-character-set=...
-e, --execute=...
-E, --vertical
\G.
-f, --force
-g, --no-named-commands
-G, --enable-named-commands
-i, --ignore-space
-h, --host=...
-H, --html
-X, --xml
-L, --skip-line-numbers
--no-pager
--no-tee
-n, --unbuffered
-N, --skip-column-names
-O, --set-variable=name=value
--help lists variables.
Please note that --set-variable=name=value and -O name=value
syntax is deprecated as of MySQL 4.0. Use --name=value instead.
-o, --one-database
--pager[=...]
ENV variable PAGER. Valid
pagers are less, more, cat [> filename], etc. See interactive help (\h)
also. This option does not work in batch mode. Pager works only in Unix.
-p[password], --password[=...]
-p you can't have a space between the option and the
password.
-P port_num, --port=port_num
--protocol=(TCP | SOCKET | PIPE | MEMORY)
-q, --quick
-r, --raw
--batch
--reconnect
-s, --silent
-S --socket=...
-t --table
-T, --debug-info
--tee=...
-u, --user=#
-U, --safe-updates[=#], --i-am-a-dummy[=#]
UPDATE and DELETE that uses keys. See below for
more information about this option. You can reset this option if you have
it in your `my.cnf' file by using --safe-updates=0.
-v, --verbose
-V, --version
-w, --wait
You can also set the following variables with -O or
--set-variable.
Please note that --set-variable=name=value and -O name=value
syntax is deprecated as of MySQL 4.0. Use --name=value instead.
| Variable Name | Default | Description |
| connect_timeout | 0 | Number of seconds before connection timeout. |
| local-infile | 0 | Disable (0) or enable (1) LOCAL capability for LOAD DATA INFILE |
| max_allowed_packet | 16777216 | Max packet length to send to/receive from server |
| net_buffer_length | 16384 | Buffer for TCP/IP and socket communication |
| select_limit | 1000 | Automatic limit for SELECT when using --safe-updates |
| max_join_size | 1000000 | Automatic limit for rows in a join when using --safe-updates |
If the mysql client loses connection to the server while
sending it a query, it will immediately and automatically try to
reconnect once to the server and send the query again.
Note that even if it succeeds in reconnecting, as your first
connection has ended, all your previous session objects are lost: temporary
tables, user and session variables. Therefore, the above behavior may
be dangerous for you, as in this example where the server was shut
down and restarted without you knowing it:
mysql> SET @a=1; Query OK, 0 rows affected (0.05 sec) mysql> INSERT INTO t VALUES(@a); ERROR 2006: MySQL server has gone away No connection. Trying to reconnect... Connection id: 1 Current database: test Query OK, 1 row affected (1.30 sec) mysql> SELECT * FROM t; +------+ | a | +------+ | NULL | +------+ 1 row in set (0.05 sec) |
The @a user variable has been lost with the connection, and
after the reconnection it is undefined.
To protect from this risk, you can start the mysql client
with the --disable-reconnect option.
If you type 'help' on the command-line, mysql will print out the
commands that it supports:
mysql> help
MySQL commands:
help (\h) Display this text.
? (\h) Synonym for `help'.
clear (\c) Clear command.
connect (\r) Reconnect to the server.
Optional arguments are db and host.
delimiter (\d) Set query delimiter.
edit (\e) Edit command with $EDITOR.
ego (\G) Send command to mysql server,
display result vertically.
exit (\q) Exit mysql. Same as quit.
go (\g) Send command to mysql server.
nopager (\n) Disable pager, print to stdout.
notee (\t) Don't write into outfile.
pager (\P) Set PAGER [to_pager].
Print the query results via PAGER.
print (\p) Print current command.
prompt (\R) Change your mysql prompt.
quit (\q) Quit mysql.
rehash (\#) Rebuild completion hash.
source (\.) Execute an SQL script file.
Takes a file name as an argument.
status (\s) Get status information from the server.
system (\!) Execute a system shell command.
tee (\T) Set outfile [to_outfile].
Append everything into given outfile.
use (\u) Use another database.
Takes database name as argument.
|
The edit, nopager, pager, and system commands
work only in Unix.
The status command gives you some information about the
connection and the server you are using. If you are running in the
--safe-updates mode, status will also print the values for
the mysql variables that affect your queries.
A useful startup option for beginners (introduced in MySQL
Version 3.23.11) is --safe-updates (or --i-am-a-dummy for
users that once may have done a DELETE FROM table_name but forgot
the WHERE clause). When using this option, mysql sends
the following command to the MySQL server when opening the connection:
SET SQL_SAFE_UPDATES=1,SQL_SELECT_LIMIT=#select_limit#,
SQL_MAX_JOIN_SIZE=#max_join_size#"
|
where #select_limit# and #max_join_size# are variables that
can be set from the mysql command-line. See section SET.
The effect of the above is:
UPDATE or DELETE statement
if you don't have a key constraint in the WHERE part. One can,
however, force an UPDATE/DELETE by using LIMIT:
UPDATE table_name SET not_key_column=# WHERE not_key_column=# LIMIT 1; |
#select_limit# rows.
SELECT statements that will probably need to examine more than
#max_join_size row combinations will be aborted.
Some useful hints about the mysql client:
Some data is much more readable when displayed vertically, instead of the usual horizontal box type output. For example longer text, which includes new lines, is often much easier to be read with vertical output.
mysql> SELECT * FROM mails WHERE LENGTH(txt) < 300 lIMIT 300,1\G
*************************** 1. row ***************************
msg_nro: 3068
date: 2000-03-01 23:29:50
time_zone: +0200
mail_from: Monty
reply: monty@no.spam.com
mail_to: "Thimble Smith" <tim@no.spam.com>
sbj: UTF-8
txt: >>>>> "Thimble" == Thimble Smith writes:
Thimble> Hi. I think this is a good idea. Is anyone familiar with UTF-8
Thimble> or Unicode? Otherwise, I'll put this on my TODO list and see what
Thimble> happens.
Yes, please do that.
Regards,
Monty
file: inbox-jani-1
hash: 190402944
1 row in set (0.09 sec)
|
For logging, you can use the tee option. The tee can be
started with option --tee=..., or from the command-line
interactively with command tee. All the data displayed on the
screen will also be appended into a given file. This can be very useful
for debugging purposes also. The tee can be disabled from the
command-line with command notee. Executing tee again
starts logging again. Without a parameter the previous file will be
used. Note that tee will flush the results into the file after
each command, just before the command-line appears again waiting for the
next command.
Browsing, or searching the results in the interactive mode in Unix less,
more, or any other similar program, is now possible with option
--pager[=...]. Without argument, mysql client will look
for the PAGER environment variable and set pager to that.
pager can be started from the interactive command-line with
command pager and disabled with command nopager. The
command takes an argument optionally and the pager will be set to
that. Command pager can be called without an argument, but this
requires that the option --pager was used, or the pager
will default to stdout. pager works only in Unix, since it uses
the popen() function, which doesn't exist in Windows. In Windows, the
tee option can be used instead, although it may not be as handy
as pager can be in some situations.
A few tips about pager:
mysql> pager cat > /tmp/log.txt |
pager:
mysql> pager less -n -i -S |
-S. You may find it very useful when
browsing the results; try the option with horizontal output (end
commands with \g, or `;') and with vertical output (end commands with
\G). Sometimes a very wide result set is hard to be read from the screen,
with option -S to less you can browse the results within the interactive
less from left to right, preventing lines longer than your screen from
being continued to the next line. This can make the result set much more
readable. You can switch the mode between on and off within the interactive
less with -S. See the 'h' for more help about less.
mysql> pager cat | tee /dr1/tmp/res.txt | \ tee /dr2/tmp/res2.txt | less -n -i -S |
You can also combine the two functions above; have the tee
enabled, pager set to 'less' and you will be able to browse the
results in Unix 'less' and still have everything appended into a file
the same time. The difference between Unix tee used with the
pager and the mysql client in-built tee, is that
the in-built tee works even if you don't have the Unix tee
available. The in-built tee also logs everything that is printed
on the screen, where the Unix tee used with pager doesn't
log quite that much. Last, but not least, the interactive tee is
more handy to switch on and off, when you want to log something into a
file, but want to be able to turn the feature off sometimes.
From MySQL version 4.0.2 it is possible to change the prompt in the
mysql command-line client.
You can use the following prompt options:
| Option | Description |
| \v | mysqld version |
| \d | database in use |
| \h | host connected to |
| \p | port connected on |
| \u | username |
| \U | full username@host |
| \\ | `\' |
| \n | new line break |
| \t | tab |
| \ | space |
| \_ | space |
| \R | military hour time (0-23) |
| \r | standard hour time (1-12) |
| \m | minutes |
| \y | two digit year |
| \Y | four digit year |
| \D | full date format |
| \s | seconds |
| \w | day of the week in three letter format (Mon, Tue, ...) |
| \P | am/pm |
| \o | month in number format |
| \O | month in three letter format (Jan, Feb, ...) |
| \c | counter that counts up for each command you do |
`\' followed by any other letter just becomes that letter.
You may set the prompt in the following places:
MYSQL_PS1 environment variable to a prompt string. For
example:
shell> export MYSQL_PS1="(\u@\h) [\d]> " |
prompt option in any MySQL configuration file, in the
mysql group. For example:
[mysql] prompt=(\u@\h) [\d]>\_ |
--prompt option on the command line to mysql.
For example:
shell> mysql --prompt="(\u@\h) [\d]> " (user@host) [database]> |
prompt (or \R) command to change your
prompt interactively. For example:
mysql> prompt (\u@\h) [\d]>\_ PROMPT set to '(\u@\h) [\d]>\_' (user@host) [database]> (user@host) [database]> prompt Returning to default PROMPT of mysql> mysql> |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |