Home > Articles > Data > MySQL

This chapter is from the book

This chapter is from the book

Tips for Interacting with mysql

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 and how to enter statements without typing each one by hand.

Simplifying the Connection Process

When 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:

  • 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.

Using an Option File

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 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:


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:


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 History

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 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 Scripts

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'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 Typing

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 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:

  • Use mysql's input line-editing facility.

  • Use copy and paste.

  • Run mysql in batch mode.

Using the mysql Input Line Editor

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 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/.

Table 1.4 mysql Input Editing Commands

Key Sequence


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 b

Move backward one word

Escape f

Move forward one word


Move cursor to beginning of line


Move cursor to end of line


Delete character under cursor


Delete character to left of cursor

Escape D

Delete word

Escape Backspace

Delete word to left of cursor


Erase everything from cursor to end of line


Undo last change; may be repeated

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:

  1. Press Left arrow or Ctrl-B a few times to move the cursor left until it's on the "s".

  2. Press Delete twice to erase the "er".

  3. Type "re" to fix the error.

  4. 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 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 Statements

If 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:

  1. Invoke mysql in a terminal window or a DOS console window.

  2. Open the file containing your statements in a document window. (For example, I use vi on Unix and gvim on Windows.)

  3. To execute a statement stored in your file, select it in the document and copy it. Then switch to your terminal window or DOS console and paste the statement 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 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 Mode

It'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;

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020