Previous Section  < Day Day Up >  Next Section

3.2 The mysql Client Program

The mysql client program enables you to send queries to the MySQL server and receive their results. It can be used interactively or it can read query input from a file in batch mode:

  • Interactive mode is useful for day-to-day usage, for quick one-time queries, and for testing how queries work.

  • Batch mode is useful for running queries that have been prewritten. It's especially valuable for issuing a complex series of queries that's difficult to enter manually, or queries that need to be run automatically by a job scheduler without user intervention.

3.2.1 Using mysql Interactively

To invoke mysql interactively from the command line, specify any necessary connection parameters after the command name:






shell> mysql -u user_name -p -h host_name


You can also provide a database name to select that database as the default database:






shell> mysql -u user_name -p -h host_name database_name


After mysql has connected to the MySQL server, it prints a mysql> prompt to indicate that it's ready to accept queries. To issue a query, enter it at the prompt. Complete the query with a statement terminator (typically a semicolon). The terminator tells mysql that the statement has been entered completely and should be executed. When mysql sees the terminator, it sends the query to the server and then retrieves and displays the result. For example:






mysql> SELECT DATABASE();

+------------+

| DATABASE() |

+------------+

| world      |

+------------+


A terminator is necessary after each statement because mysql allows several queries to be entered on a single input line. mysql uses the terminators to distinguish where each query ends, and then sends each one to the server in turn and displays its results:






mysql> SELECT DATABASE(); SELECT VERSION();

+------------+

| DATABASE() |

+------------+

| world      |

+------------+

+------------+

| VERSION()  |

+------------+

| 4.0.18-log |

+------------+


Statement terminators are necessary for another reason as well: mysql allows a single query to be entered using multiple input lines. This makes it easier to issue a long query because you can enter it over the course of several lines. mysql will wait until it sees the statement terminator before sending the query to the server to be executed. For example:






mysql> SELECT Name, Population FROM City

    -> WHERE Country = 'IND'

    -> AND Population > 3000000;

+--------------------+------------+

| Name               | Population |

+--------------------+------------+

| Mumbai (Bombay)    |   10500000 |

| Delhi              |    7206704 |

| Calcutta [Kolkata] |    4399819 |

| Chennai (Madras)   |    3841396 |

+--------------------+------------+


More information about statement terminators can be found in section 3.2.3, "Statement Terminators."

In the preceding example, notice what happens when you don't complete the query on a single input line: mysql changes the prompt from mysql> to -> to indicate that it's still waiting to see the end of the statement. The full set of mysql prompts is discussed in section 3.2.4, "The mysql Prompts."

If a statement results in an error, mysql displays the error message returned by the server:






mysql> This is an invalid statement;

ERROR 1064: You have an error in your SQL syntax.


If you change your mind about a statement that you're composing, enter \c and mysql will return you to a new prompt:






mysql> SELECT Name, Population FROM City

    -> WHERE \c

mysql>


To quit mysql, use \q, QUIT, or EXIT:






mysql> \q


3.2.2 Using Editing Keys in mysql

mysql supports input-line editing, which enables you to recall and edit input lines. For example, you can use the up-arrow and down-arrow keys to move up and down through previous input lines, and the left-arrow and right-arrow keys to move back and forth within a line. Other keys, such as Backspace and Delete, erase characters from the line, and you can type in new characters at the cursor position. To submit an edited line, press Enter.

On Windows, you might find that input-line editing does not work for Windows 95, 98, or Me.

mysql also supports tab-completion to make it easier to enter queries. With tab-completion, you can enter part of a keyword or identifier and complete it using the Tab key. This feature is supported on Unix only.

3.2.3 Statement Terminators

You may use any of several statement terminators to end a query. Two statement terminators are the semicolon character (;) and the \g sequence. They're equivalent and may be used interchangeably:






mysql> SELECT VERSION(), DATABASE();

+------------+------------+

| VERSION()  | DATABASE() |

+------------+------------+

| 4.0.18-log | world      |

+------------+------------+

mysql> SELECT VERSION(), DATABASE()\g

+------------+------------+

| VERSION()  | DATABASE() |

+------------+------------+

| 4.0.18-log | world      |

+------------+------------+


The \G sequence also terminates queries, but causes mysql to display query results in a different style. The new style shows each output row with each column value on a separate line:






mysql> SELECT VERSION(), DATABASE()\G

*************************** 1. row ***************************

 VERSION(): 4.0.18-log

DATABASE(): world


The \G terminator is especially useful if a query produces very wide output lines. It can make the result much easier to read.

3.2.4 The mysql Prompts

The mysql> prompt displayed by mysql is just one of several different prompts that you might see when entering queries. Each type of prompt has a functional significance because mysql varies the prompt to provide information about the status of the statement you're entering. The following table shows each of these prompts:

Prompt

Meaning of Prompt

mysql>

Ready for new statement

->

Waiting for next line of statement

'>

Waiting for end of single-quoted string

">

Waiting for end of double-quoted string or identifier

`>

Waiting for end of backtick-quoted identifier


The mysql> prompt is the main (or primary) prompt. It signifies that mysql is ready for you to begin entering a new statement.

The other prompts are continuation (or secondary) prompts. mysql displays them to indicate that it's waiting for you to finish entering the current statement. The -> prompt is the most generic continuation prompt. It indicates that you have not yet completed the current statement, for example, by entering ; or \G. The '>, ">, and `> prompts are more specific. They indicate not only that you're in the middle of entering a statement, but that you're in the middle of entering a single-quoted string, a double-quoted string, or a backtick-quoted identifier, respectively. When you see one of these prompts, you'll often find that you have entered an opening quote on the previous line without also entering the proper closing quote.

If in fact you did mistype the current query by forgetting to close a quote, you can cancel the query by entering the closing quote followed by the \c clear-query command.

3.2.5 Using Script Files with mysql

When used interactively, mysql reads queries entered at the keyboard. mysql can also accept input from a file. An input file containing SQL statements to be executed is known as a "script file" or a "batch file." A script file should be a plain text file containing statements in the same format that you would use to enter the statements interactively. In particular, each statement must end with a terminator.

One way to process a script file is to execute it with a SOURCE command from within mysql:






mysql> SOURCE input_file;


Notice that there are no quotes around the name of the file.

mysql executes the queries in the file and displays any output produced.

The file must be located on the client host where you're running mysql. The filename must either be an absolute pathname listing the full name of the file, or a pathname that's specified relative to the directory in which you invoked mysql. For example, if you started mysql on a Windows machine in the C:\mysql\directory and your script file is my_commands in the C:\scripts directory, either of the following SOURCE commands would tell mysql to run the file:






mysql> SOURCE C:\scripts\my_commands;

mysql> SOURCE ..\scripts\my_commands;


The other way to execute a script file is by naming it on the mysql command line. Invoke mysql and use the < input redirection operator to specify the file from which to read query input:






shell> mysql db_name < input_file


If a statement in a script file fails with an error, mysql ignores the rest of the file. To execute the entire file regardless of whether errors occur, invoke mysql with the --force or -f option.

A script file can itself contain SOURCE commands to execute other files. But be careful not to create a SOURCE loop. For example, if file1 contains a SOURCE file2 command, file2 should not contain a SOURCE file1 command.

3.2.6 mysql Output Formats

By default, mysql produces output in one of two formats, depending on whether you use it in interactive or batch mode:

  • When invoked interactively, mysql displays query output in a tabular format that uses bars and dashes to display values lined up in boxed columns.

  • When you invoke mysql with a file as its input source on the command line, mysql runs in batch mode with query output displayed using tab characters between data values.

To override the default output format, use these options:

  • --batch or -B

    Produce batch mode (tab-delimited) output, even when running interactively.

  • --table or -t

    Produce tabular output format, even when running in batch mode.

In batch mode, you can use the --raw or -r option to suppress conversion of characters such as newline and carriage return to escape-sequences like \n or \r. In raw mode, the characters are printed literally.

To select a different output format than either of the default formats, use these options:

  • --html or -H

    Produce output in HTML format.

  • --xml or -X

    Produce output in XML format.

3.2.7 mysql Client Commands and SQL Statements

When you issue an SQL statement while running mysql, the program sends the statement to the MySQL server to be executed. SELECT, INSERT, UPDATE, and DELETE are examples of this type of input. mysql also understands a number of its own commands that aren't SQL statements. The QUIT and SOURCE commands that have already been discussed are examples of mysql commands. Another example is STATUS, which displays information about the current connection to the server, as well as status information about the server itself. Here is what a status display might look like:






mysql> STATUS;

--------------

mysql  Ver 12.22 Distrib 4.0.18, for apple-darwin7.2.0 (powerpc)





Connection id:          14498

Current database:       world

Current user:           myname@localhost

SSL:                    Not in use

Current pager:          stdout

Using outfile:          ''

Server version:         4.0.18-log

Protocol version:       10

Connection:             Localhost via UNIX socket

Client characterset:    latin1

Server characterset:    latin1

UNIX socket:            /tmp/mysql.sock

Uptime:                 15 days 1 hour 9 min 27 sec



Threads: 4  Questions: 78712  Slow queries: 0  Opens: 786  Flush tables: 1

Open tables: 64  Queries per second avg: 0.061

--------------


A full list of mysql commands can be obtained using the HELP command.

mysql commands have both a long form and a short form. The long form is a full word (such as SOURCE, STATUS, or HELP). The short form consists of a backslash followed by a single character (such as \., \s, or \h). The long forms may be given in any lettercase. The short forms are case sensitive.

Unlike SQL statements, mysql commands cannot be entered over multiple lines. For example, if you issue a SOURCE file_name command to execute statements stored in a file, file_name must be given on the same line as SOURCE. It may not be entered on the next line.

By default, the short command forms are recognized on any input line, except within quoted strings. The long command forms aren't recognized except at the mysql> primary prompt. For example, CLEAR and \c both clear (cancel) the current command, which is useful if you change your mind about issuing the statement that you're currently entering. But CLEAR isn't recognized after the first line of a multiple-line statement, so you should use \c instead. To have mysql recognize the long command names on any input line, invoke it with the --named-commands option.

3.2.8 Using the --safe-updates Option

It's possible to inadvertently issue statements that modify many rows in a table or that return extremely large result sets. The --safe-updates option helps prevent these problems. The option is particularly useful for people who are just learning to use MySQL. --safe-updates has the following effects:

  • UPDATE and DELETE statements are allowed only if they include a WHERE clause that specifically identifies which records to update or delete by means of a key value, or if they include a LIMIT clause.

  • Output from single-table SELECT statements is restricted to no more than 1,000 rows unless the statement includes a LIMIT clause.

  • Multiple-table SELECT statements are allowed only if MySQL will examine no more than 1,000,000 rows to process the query.

The --i-am-a-dummy option is a synonym for --safe-updates.

    Previous Section  < Day Day Up >  Next Section