Cry MySQL How to...

Connect to a MySQL database using the mysql command line tool


MySQL provides a useful command line tool called "mysql" for connecting to, and interacting with, a MySQL database.

Database on same computer

To connect to a database on the same computer:

mysql -u<account> -p<password>

where

  • <account> is the account to use when connecting
  • <password> is the password to use. If you specify -p with no password then you will be prompted to enter the password.

So for example:

mysql -uroot -psecret

would connect using the account "root" and the password "secret".

MySQL supports a longer and clearer way of specifying these command line parameters, so the following is equivalent to the last example:

mysql --user=root --password=secret

Database on different computer

To connect to a database on a different computer:

mysql -u<account> -p<password> -h<computer>

where

  • <account> is the account to use when connecting
  • <password> is the password to use. If you specify -p with no password then you will be prompted to enter the password.
  • <computer> is the name of the computer to connect to.

So, for example:

mysql -uroot -psecret -hcompb

would connect using the account "root", the password "secret" to the MySQL database running on the computer called "compb".

MySQL supports a longer and clearer way of specifying these command line parameters, so the following is equivalent to the last example:

mysql --user=root --password=secret --host=compb

Specifying which database

To specify which database to connect to, use:

mysql ... -d<database>

or

mysql ... -=database=<database>

so for example:

mysql --user=root --password=secret --database=census

would connect to the database called "census" on the local computer, using the account "root" and the password "secret".

General Notes

  • The mysql utility is found in the mysql\bin folder.
  • For a full list of the command line switches that the MySQL command line utility takes please refer to the MySQL documentation.

These notes have been tested against MySQL version 4



About the author: is a dedicated software developer and webmaster. For his day job he develops websites and desktop applications as well as providing IT services. He moonlights as a technical author and consultant.