Tips for Interacting with mysqlThis 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 and how to enter statements without typing each one by hand. Simplifying the Connection ProcessWhen you invoke mysql, it's likely that you need to specify connection parameters such as hostname, username, or password. 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:
Using an Option FileMySQL 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 can also be used by other MySQL clients such as mysqlimport or mysqlshow. In other words, an option file makes it easier to use not just mysql but many other programs as well. This section briefly describes how to set up an option file for use by client programs. Additional details can be found in the section "Option Files," in Appendix F, "MySQL Program Reference." 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.ini in your Windows directory or named my.cnf in the root directory of the C drive (that is, %WINDIR%\my.ini or C:\my.cnf). An option file is a plain text file; you can create it using any text editor. The file's contents should look something like this: [client] host=server_host user=your_name password=your_pass The [client] line signals the beginning of the client option group. MySQL programs read the lines following it to obtain option values, until 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, if the server is running on the host cobra.snake.net and your MySQL username and password are sampadm and secret, put these lines in the .my.cnf file: [client] host=cobra.snake.net user=sampadm password=secret The [client] line is required, to define where the option group begins, but the 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. The default host is localhost, so if you connect to a server running on the local host, no host line is necessary. Under Unix, an additional precaution that you should take after creating the option file is to set its access mode to a restrictive value to make sure that 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 Using Your Shell's Command HistoryShells 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 like this:
% !my
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. Using Shell Aliases and ScriptsIf 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's 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 the sampdb 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 need to access several databases or connect to several hosts, you can define multiple aliases, shortcuts, or scripts, each of which invokes mysql with different options. Issuing Statements with Less Typingmysql 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 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. You can use several techniques to avoid needless retyping:
Using the mysql Input Line Editormysql 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 key sequences you will find useful are shown in Table 1.4, but there are many input editing commands available in addition to 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/.
The following example describes a simple use for input editing. Suppose that 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 you can fix the query like this:
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 supports the arrow keys for moving up and down through input lines or left and right within lines, but not the other editing commands. Using Copy and Paste to Issue StatementsIf you work in a windowing environment, the text of statements that you find useful can be saved in a file and recalled by copy and paste operations. Simply follow this procedure:
The procedure sounds cumbersome when written out like that, but when you're actually carrying it out, it provides a way to enter statements quickly and with no typing. With a little practice, it becomes second nature. You can use copy and paste in the other direction, too (from your terminal window to your statement file). On Unix, when you enter statements in mysql, they are saved in a file named .mysql_history in your home directory. If you manually enter a statement that you want to save for further reference, quit mysql, open .mysql_history in an editor, and then copy and paste the statement from .mysql_history into your statement file. Running mysql in Batch ModeIt's not necessary to run mysql interactively. mysql can read input from a file in non-interactive (batch) mode. This is useful for statements that you run periodically because you certainly don't want to retype them every time you run them. It's easier to put the statements into a file once, and then have mysql execute the contents of the file as needed. Suppose that 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, you can write the query like this: 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 execute it by feeding it to mysql like this:
% 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 table-format 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 If you are already running mysql, execute the contents of the file by using a source command:
mysql> source interests.sql
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 that 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, … 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 is located in the misc directory of the sampdb distribution. An equivalent Windows batch file, interests.bat, is provided there as well. |