This section discusses how to interact with the mysql client program more efficiently and with less typing. It also describes how to connect to the server more easily, how to enter queries without typing each one by hand, and how to change the prompt if you don't like the default prompt.
It's likely that you need to specify connection parameters, such as hostname, username, or password when you invoke mysql. That's a lot of typing just to run a program and it gets tiresome very quickly. There are several ways to minimize the amount of typing necessary to establish a connection to the MySQL server:
Store connection parameters in an option file.
Repeat commands by taking advantage of your shell's command history capabilities.
Define a mysql command line shortcut using a shell alias or script.
As of version 3.22.10, MySQL allows you to store connection parameters in an option file. Then you don't have to type the parameters each time you run mysql; they are used just as if you had entered them on the command line. A big advantage of this technique is that the parameters will also be used by other MySQL clients, such as mysqlimport. In other words, an option file makes it easier to use not just mysql but many other programs as well.
Under UNIX, you set up an option file by creating a file named ~/.my.cnf (that is, a file named .my.cnf in your home directory). Under Windows, create an option file named my.cnf in the root directory of the C drive or named my.ini in your Windows system directory (that is, C:\my.cnf or %SYSTEM%\my.ini). An option file is a plain text file, so you can create it using any text editor. The file's contents look something like the following:
[client] host=server_host user=your_name password=your_pass
The [client] line signals the beginning of the client option group; any lines following it are read by MySQL client programs to obtain option values through the end of the file or until a different option group begins. Replace server_host, your_name, and your_pass with the hostname, username, and password that you specify when you connect to the server. For example, .my.cnf might look like this:
[client] host=cobra.snake.net user=sampadm password=secret
The [client] line is required to define where the option group begins, but lines that define parameter values are optional. You can specify just the ones you need. For example, if you're using UNIX and your MySQL username is the same as your UNIX login name, there is no need to include a user line. If you connect to localhost, no host line is necessary.
After creating the option file, an additional precaution you should take under UNIX is to set the file's access mode to a restrictive value to make sure no one else can read or modify it. Either of the following commands make the file accessible only to you:
% chmod 600 .my.cnf % chmod u=rw,go-rwx .my.cnf
More information on option files may be found in Appendix E.
Shells such as tcsh and bash remember your commands in a history list and allow you to repeat commands from that list. If you use such a shell, your history list can help you avoid typing entire commands. For example, if you've recently invoked mysql, you can execute it again, as follows:
The ! character tells your shell to search through your command history to find the most recent command that begins with "my" and reissue it as though you'd typed it again yourself. Some shells also allow you to move up and down through your history list using the Up arrow and Down arrow keys (or perhaps Ctrl-P and Ctrl-N). You can select the command you want this way and then press Enter to execute it. tcsh and bash have this facility, and other shells may as well. Check the documentation for your shell to find out more about using your history list.
If your shell provides an alias facility, you can set up a short command name that maps to a long command. For example, in csh or tcsh, you can use the alias command to set up an alias named sampdb like this:
alias sampdb 'mysql -h cobra.snake.net -p -u sampadm sampdb'
The syntax for bash is slightly different:
alias sampdb='mysql -h cobra.snake.net -p -u sampadm sampdb'
Defining the alias makes the following two commands equivalent:
% sampdb % mysql -h cobra.snake.net -p -u sampadm sampdb
Clearly, the first is easier to type than the second. To make the alias take effect each time you log in, put the alias command in one of your shell's startup files (for example, .tcshrc for tcsh, or .bash_profile for bash).
Under Windows, a similar technique is to create a shortcut that points to the mysql program and then edit the shortcut properties to include the appropriate connection parameters.
Another way to invoke commands with less typing is to create a script that executes mysql for you with the proper options. In UNIX, a shell script that is equivalent to the sampdb alias just shown looks like this:
#! /bin/sh exec mysql -h cobra.snake.net -p -u sampadm sampdb
If you name the script sampdb and make it executable (with chmod +x sampdb), you can type sampdb at the command prompt to run mysql and connect to my database.
Under Windows, a batch file can be used to do the same thing. Name the file sampdb.bat and put the following line in it:
mysql -h cobra.snake.net -p -u sampadm sampdb
This batch file can be run either by typing sampdb at the prompt in a DOS console or by double-clicking its Windows icon.
If you access multiple databases or connect to multiple hosts, you can define several aliases, shortcuts, or scripts, each of which invokes mysql with different options.
mysql is an extremely useful program for interacting with your database, but its interface is most suitable for short, single-line queries. It's true that mysql itself doesn't care whether or not a query spreads across multiple lines, but long queries aren't much fun to type. Nor is it very entertaining to enter a query, even a short one, only to discover that you must retype it because it has a syntax error. There are several techniques you can use to avoid needless typing and retyping:
Use mysql's input line-editing facility.
Use copy and paste.
Run mysql in batch mode.
mysql has the GNU Readline library built in to allow input line editing. You can manipulate the line you're currently entering or you can recall previous input lines and re-enter them, either as is or after further modification. This is convenient when you're entering a line and spot a typo; you can back up within the line to correct the problem before pressing Enter. If you enter a query that has a mistake in it, you can recall the query, edit it to fix the problem, and then resubmit it. (This is easiest if you type the entire query on one line.)
Some of the editing sequences you will find useful are shown in Table 1.4, but there are many input editing commands available besides those shown in the table. You can read about them in the command editing chapter of the bash manual, available online from the GNU Project Web site at http://www.gnu.org/manual/.
|Up arrow or Ctrl-P||Recall previous line|
|Down arrow or Ctrl-N||Recall next line|
|Left arrow or Ctrl-B||Move cursor left (backward)|
|Right arrow or Ctrl-F||Move cursor right (forward)|
|Escape Ctrl-B||Move backward one word|
|Escape Ctrl-F||Move forward one word|
|Ctrl-A||Move cursor to beginning of line|
|Ctrl-E||Move cursor to end of line|
|Ctrl-D||Delete character under cursor|
|Delete||Delete character to left of cursor|
|Escape D||Delete word|
|Escape Backspace||Delete word to left of cursor|
|Ctrl-K||Erase everything from cursor to end of line|
|Ctrl-_||Undo last change; may be repeated|
The following example describes a simple use for input editing. Suppose you've entered this query while using mysql:
mysql> SHOW COLUMNS FROM persident;
If you notice that you've misspelled president as persident before pressing Enter, press Left arrow or Ctrl-B a few times to move the cursor left until it's on the s. Then press Delete twice to erase the er, type re to fix the error, and press Enter to issue the query. If you press Enter before you notice the misspelling, that's not a problem. After mysql displays its error message, press up arrow or Ctrl-P to recall the line and then edit it as just described.
Under Windows, the Readline editing capabilities are not available in mysql. (If you're using a Windows NT-based system, mysql will support the arrow keys for moving up and down through input lines or left and right within lines, but not the other editing commands.) To take advantage of the full set of input editing commands, you can use the mysqlc program, which is like mysql but is built with the Cygnus libraries that include Readline support. For details on making sure mysqlc is installed correctly, see the entry for mysql in Appendix E.
If you work in a windowing environment, the text of queries that you find useful can be saved in a file and recalled by copy and paste operations. Simply perform the following steps:
Invoke mysql in a terminal window or a DOS console window.
Open the file containing your queries in a document window (for example, I use vi on UNIX, gvim on Windows, and BBEdit on Mac OS).
To execute a query stored in your file, select it in the document and copy it. Then switch to your terminal window or DOS console and paste the query into mysql.
The procedure sounds cumbersome when written out like that, but when you're actually carrying it out, it provides a way to enter queries quickly and with no typing.
This technique also allows you to edit your queries in the document window, and it allows you to construct new queries by copying and pasting pieces of existing queries. For example, if you often select rows from a particular table but like to view the output sorted in different ways, you can keep a list of different ORDER BY clauses in your document window and then copy and paste the one you want to use for any particular query.
You can use copy and paste in the other direction, too (from your terminal window to your query file). When you enter lines in mysql, they are saved in a file named .mysql_history in your home directory. If you manually enter a query that you want to save for further reference, quit mysql, open .mysql_history in an editor, and then copy and paste the query from .mysql_history into your query file.
It's not necessary to run mysql interactively. mysql can read input from a file in non-interactive (batch) mode. This is useful for queries that you run periodically because you certainly don't want to retype such a query every time you run it. It's easier to put it into a file once and then have mysql execute the contents of the file as needed.
Suppose you have a query that finds Historical League members who have an interest in a particular area of U.S. history by looking in the interests column of the member table. For example, to find members with an interest in the Great Depression, the query could be written as follows:
SELECT last_name, first_name, email, interests FROM member WHERE interests LIKE '%depression%' ORDER BY last_name, first_name;
Put the query in a file interests.sql and then run it by feeding it to mysql as follows:
% mysql sampdb < interests.sql
By default, mysql produces output in tab-delimited format when run in batch mode. If you want the same kind of tabular ("boxed") output you get when you run mysql interactively, use the -t option:
% mysql -t sampdb < interests.sql
If you want to save the output, redirect it to a file:
% mysql -t sampdb < interests.sql > output_file
To use the query to find members with an interest in Thomas Jefferson, you could edit the query file to change depression to Jefferson and then run mysql again. That works okay as long as you don't use the query very often. If you do, a better method is needed. One way to make the query more flexible is to put it in a shell script that takes an argument from the script command line and uses it to change the text of the query. That parameterizes the query so that you can specify the interests value when you run the script. To see how this works, write a little shell script, interests.sh:
#! /bin/sh # interests.sh - find USHL members with particular interests if [ $# -ne 1 ]; then echo 'Please specify one keyword'; exit; fi mysql -t sampdb <<QUERY_INPUT SELECT last_name, first_name, email, interests FROM member WHERE interests LIKE '%$1%' ORDER BY last_name, first_name; QUERY_INPUT
The third line makes sure there is one argument on the command line; it prints a short message and exits otherwise. Everything between <<QUERY_INPUT and the final QUERY_INPUT line becomes the input to mysql. Within the text of the query, the shell replaces the reference to $1 with the argument from the command line. (In shell scripts, $1, $2, and so on refer to the command arguments.) This causes the query to reflect whatever keyword you specify on the command line when you run the script.
Before you can run the script, you must make it executable:
% chmod +x interests.sh
Now you don't need to edit the script each time you run it. Just tell it what you're looking for on the command line:
% interests.sh depression % interests.sh Jefferson
The interests.sh script can be found in the misc directory of the sampdb distribution. An equivalent Windows batch file, interests.bat, is provided there as well.
As of MySQL 4.0.2, you can change the primary mysql prompt if you don't like it. For example, to include the name of the current database in the prompt, use the PROMPT command as follows and then select different databases to see how the prompt follows the current selection:
% mysql mysql> PROMPT \d>\_ PROMPT set to '\d>\_' (none)> USE sampdb; Database changed sampdb> USE test; Database changed test>
The PROMPT keyword is followed by the prompt string that you want to use. Within the string, sequences that begin with backslashes indicate special prompt options. The \d and \_ sequences signify the current database name and a space; for a complete list of available options, see the entry for mysql in Appendix E.