How to Connect to MySQL from Command Line Quickly
To connect to MySQL from the command line, use the
mysql command followed by -u for username and -p to prompt for your password. For example, mysql -u username -p will start the MySQL client and ask for your password to connect.Syntax
The basic syntax to connect to MySQL from the command line is:
mysql: The command to start the MySQL client.-u username: Specifies the MySQL user to connect as.-p: Prompts for the user's password securely.-h hostname(optional): Specifies the server address if not local.database_name(optional): Connect directly to a specific database.
bash
mysql -u username -p mysql -u username -p -h hostname database_name
Example
This example shows how to connect to MySQL locally as user root. After running the command, you will be prompted to enter the password securely.
bash
mysql -u root -p
Output
Enter password: ********
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 10
Server version: 8.0.33 MySQL Community Server - GPL
mysql>
Common Pitfalls
Common mistakes when connecting to MySQL from the command line include:
- Forgetting the
-pflag and expecting a password prompt. - Typing the password directly after
-pwithout a space (e.g.,-ppassword), which is insecure and not recommended. - Not specifying the correct hostname if connecting to a remote server.
- Using the wrong username or password.
Always use -p alone to be prompted for the password securely.
bash
Wrong: mysql -u root -ppassword Right: mysql -u root -p
Quick Reference
| Option | Description | Example |
|---|---|---|
| -u username | Specify MySQL username | mysql -u root -p |
| -p | Prompt for password | mysql -u user -p |
| -h hostname | Connect to remote host | mysql -u user -p -h 192.168.1.10 |
| database_name | Connect directly to a database | mysql -u user -p mydatabase |
Key Takeaways
Use
mysql -u username -p to connect and securely enter your password.Add
-h hostname if connecting to a remote MySQL server.Avoid typing the password directly after
-p to keep it secure.You can specify a database name to connect directly to it.
If you see connection errors, check username, password, and host details.