DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk10 min

How to Access MySQL From the Command Line

Use mysql -u user -p for an interactive login, add -h and -P for remote or custom-port servers, and choose 127.0.0.1 or --protocol=TCP when Unix localhost would select a socket.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use the MySQL client with an account name and a prompted password:

mysql -u user -p

For another machine, add the server name and, when needed, its TCP port:

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
mysql -h db.example.com -P 3306 -u user -p

The first command normally connects to a local server using the platform’s default transport. On Unix-like systems, localhost usually means a Unix socket rather than TCP, so use 127.0.0.1 or --protocol=TCP when you specifically need a network connection. The -p option without a value is intentional: it makes the client ask for the password without putting the secret in the command itself.

What you need before running the client

A syntactically correct command can still fail if the surrounding setup is not ready. Confirm these prerequisites first:

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.
  • A MySQL server is running and accepting the transport you intend to use.
  • The command-line client is installed and available in your shell, or you are running it from the installation’s client directory.
  • You have a valid MySQL account name and password.
  • Your account is permitted to connect from the host where you run the client.
  • For a remote connection, the hostname or address resolves to the intended server, the selected port is reachable, and any firewall or network policy allows the connection.
  • If the server requires a particular authentication plugin or TLS configuration, the client and server settings must be compatible.

These conditions are independent of command syntax. A command can be written correctly while the server is stopped, listening on another port, restricted to a different source host, or requiring security settings that the client has not been given.

Understand the command options

The standard interactive pattern is built from four options. Option values are separated from the option by a space in the examples below.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Option Purpose When to use it
-u user or --user=user Selects the MySQL account. Replace user with the account that should authenticate.
-p Prompts for the account password interactively. Use the bare option for normal logins; do not append the real password in a shared shell.
-h host or --host=host Selects the MySQL server host. Required when the target is not the local default, and useful when choosing a specific local address.
-P port or --port=port Selects a TCP port. Use it for a nondefault TCP listener. The classic MySQL protocol’s documented default is TCP port 3306.

A database name can follow the options. It is optional; when supplied, it becomes the initial default database after authentication. For example:

mysql -u finley -p db_name

This does not change which server or account is used. It only asks the client to select db_name as the starting database once the login succeeds.

Connect to a local server interactively

Use the normal local login

  1. Open a terminal, Command Prompt, or the MySQL Command Line Client.
  2. Run the standard command, replacing user with your account:
mysql -u user -p
  1. When the client displays a password prompt, type the password and press Enter. The characters normally are not echoed.
  2. Wait for the mysql> prompt. That prompt indicates that the interactive client is ready to accept SQL.

If the local server uses its default local transport and your account is allowed to connect, no host or port option is needed. If you want a particular database loaded immediately, append its name as shown in the previous section.

Know what “local” means

“Local” describes where you run the client, not necessarily the transport used. On Unix, the host name localhost normally selects a Unix-socket connection. A socket is a local operating-system endpoint, so a command that names localhost can avoid TCP entirely. This distinction matters when the server is listening on a custom TCP port but the socket file or socket location is different.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Connect to a remote MySQL server

Use a hostname and the default TCP port

For a server reachable as db.example.com on the classic protocol’s default port, run:

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.
mysql -h db.example.com -u user -p

Adding -h selects the remote host. If you omit -P, the client uses the protocol’s default TCP port, 3306, unless another configuration has changed the effective setting.

Specify a custom TCP port

If the server listens on another port, include it explicitly:

mysql -h db.example.com -P 3307 -u user -p

The uppercase -P identifies the TCP port. Use the port configured on the server or supplied by the administrator; choosing an arbitrary open port does not make MySQL available there.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Connect by address

A resolvable DNS name is not required if you have a reachable address:

mysql -h 203.0.113.20 -P 3306 -u user -p

The address, port, firewall policy, server bind configuration, and account’s permitted source hosts must all agree. A successful network route alone does not grant MySQL authentication.

Choose between a Unix socket and TCP

Why localhost can ignore your port

On Unix-like systems, localhost normally means “use the local Unix socket.” Consequently, this command can still attempt a socket connection even though it contains a port number:

mysql -h localhost -P 3307 -u user -p

The -P 3307 value applies to TCP. It does not force the client to switch away from the socket implied by localhost.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

Force TCP to the local machine

Use the loopback address when you want TCP and a specific port:

mysql -h 127.0.0.1 -P 3307 -u user -p

Alternatively, keep a host name and select the protocol explicitly:

mysql --protocol=TCP -P 3307 -u user -p

These forms are useful when testing a TCP listener, reproducing the same transport used by a remote application, or diagnosing a mismatch between a socket and a port.

Name the socket explicitly

When the server’s socket is not at the client’s expected location, specify it with -S or its long form:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
mysql -S /path/to/mysql.sock -u user -p

This selects the socket path directly. It is separate from TCP port selection, so adding -P does not correct a wrong socket path.

Compare the local transport choices

Goal Example Transport selected
Use the usual local default mysql -u user -p Platform-dependent local default; on Unix, a local socket is commonly selected.
Use TCP on the loopback address mysql -h 127.0.0.1 -P 3307 -u user -p TCP to the specified port.
Force TCP explicitly mysql --protocol=TCP -P 3307 -u user -p TCP, with the port supplied.
Use a known socket file mysql -S /path/to/mysql.sock -u user -p The named Unix socket.
Try localhost with a port mysql -h localhost -P 3307 -u user -p Usually the Unix socket on Unix systems; the port may not be used.

Enter the password safely

Prefer an interactive prompt

The safest everyday form is the bare -p option:

mysql -u user -p

The client asks for the password after the command is submitted. This keeps the secret out of the command text that you just typed and avoids placing it in the process argument list in the first place.

Why -psecret is discouraged

Do not normally write a password immediately after -p, such as:

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.
mysql -u user -psecret

MySQL documentation warns that specifying a password on the command line should be considered insecure because command-line arguments can be exposed to other users or system tools. The risk is especially important on shared workstations, multi-user servers, build logs, screen recordings, shell history, and automation output.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a protected credentials mechanism for automation

For repeated or noninteractive connections, MySQL points to option files and login path files as safer places to store connection credentials than a literal command-line password. Protect the file with the operating system’s access controls and follow your organization’s secret-management policy. The exact file location and permissions vary by platform and installation, so verify them for the client environment rather than copying a path from an unrelated system.

Do not assume that hiding a password in a shell variable makes it safe: variables can also leak through debugging output, inherited environments, or scripts. A prompt is appropriate for an administrator at a terminal; a protected credentials mechanism is more suitable when a process must connect without human input.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Platform-specific transport and client notes

Linux and other Unix-like systems

Unix systems support TCP and Unix sockets for MySQL connections. The localhost socket behavior described above is the most common source of confusion when a server has a custom TCP port. Use 127.0.0.1 or --protocol=TCP for a deliberate TCP test, and -S when the socket path is known.

Windows

MySQL documents TCP, Windows named pipes, and shared memory as possible transports on Windows, with the applicable default depending on the installation and configuration. The client supports protocol selectors including:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
--protocol=TCP
--protocol=SOCKET
--protocol=PIPE
--protocol=MEMORY

Use only a protocol supported and enabled by the server and client on that machine. A command that works over TCP is not evidence that named-pipe or shared-memory connections are configured, and vice versa.

On a Windows installation that includes the bundled client, you may run the command from the MySQL installation’s bin directory or use the MySQL Command Line Client shortcut. If the shell reports that mysql is not recognized, start the bundled shortcut or change to the directory containing the client executable; adding that directory to the system path is an installation choice, not a MySQL login requirement.

Recognize a successful session and run SQL

Use the prompt as the readiness check

After authentication, the client displays:

mysql>

At that prompt, enter SQL statements. End a statement with a semicolon or with the client terminator g. For example:

SELECT CURRENT_USER();

The semicolon tells the interactive client to send the statement. If you prefer the alternate terminator, enter the statement followed by g instead.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Start in a particular database

Appending a database name to the login command requests that it be selected as the initial default database. If you omit the name, you can still connect and work with statements that fully qualify their database objects, or select a database later according to your account’s permissions.

Exit the MySQL client

At the mysql> prompt, either enter:

QUIT;

or use the short command:

q

On Unix, pressing Control-D also disconnects from the interactive client. Exiting the client ends that session; it does not stop the MySQL server.

Troubleshoot a command that does not connect

The client command is not found

This means the shell cannot locate the MySQL client executable. On Windows, launch the bundled MySQL Command Line Client or run the command from the installation’s bin directory. On other systems, use the client installation’s documented executable path or adjust the shell path for that user. This is a client-installation issue, not a password failure.

A local connection fails with a socket-related message

First decide whether you intended a socket or TCP:

  • For the socket, find the server’s actual socket path and pass it with -S /path/to/mysql.sock.
  • For TCP, replace localhost with 127.0.0.1 and include the configured port, or use --protocol=TCP.

Do not keep changing the password while the client is attempting the wrong transport. A valid account cannot authenticate through a socket that does not exist or a port where no server is listening.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A remote connection times out or is refused

Check the host name or address, then verify the server’s configured TCP port. The classic default is 3306, but administrators can choose another port. Confirm that the server is running, listening on the intended interface, and reachable through intervening firewalls or network controls. If the server binds only to a local interface, a remote client cannot reach it even when the port number is correct.

The server rejects the account

Re-enter the account name and password at the prompt, paying attention to which account you intended to use. MySQL accounts can be restricted by the host from which the connection originates, so an account that works locally may be denied remotely. Authentication plugins and required TLS settings can also differ between installations; obtain the server’s required connection policy from its administrator instead of weakening security options blindly.

The command uses the wrong port

Remember that -P controls TCP only. If the command uses -h localhost on Unix, the client may still choose a socket. Use 127.0.0.1 or --protocol=TCP to make a port test meaningful. Conversely, if the server is available only through a socket, remove the TCP assumptions and provide the correct socket path.

A script exposes the password

Replace an inline password with the bare -p prompt for interactive work. For unattended work, move credentials to a properly protected option or login path file and review who can read it. Also inspect shell history, CI logs, process listings, and debugging output for secrets that may already have been recorded.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Pick the right command for the situation

Situation Command Important qualification
Interactive login to the usual local server mysql -u user -p Uses the platform’s normal local transport; Unix commonly selects a socket.
Local server over TCP on the default port mysql -h 127.0.0.1 -P 3306 -u user -p Explicitly tests TCP rather than the Unix localhost socket behavior.
Local server over a custom TCP port mysql -h 127.0.0.1 -P 3307 -u user -p Replace 3307 with the configured listener.
Remote server on the default classic port mysql -h db.example.com -u user -p Uses the documented default TCP port, 3306, unless another setting overrides it.
Remote server on a custom port mysql -h db.example.com -P 3307 -u user -p The network path and firewall must allow that port.
Known Unix socket mysql -S /path/to/mysql.sock -u user -p Requires the exact socket path and a server listening on it.
Immediate default database mysql -u user -p db_name db_name is selected after authentication if the account can access it.

A short operational checklist

  • Start with -u user -p; let the client prompt for the password.
  • Add -h for a named or remote server.
  • Add uppercase -P only when you are selecting a TCP port.
  • Use 3306 as the classic TCP default unless the server documentation specifies another port.
  • On Unix, remember that localhost normally means a socket.
  • Use 127.0.0.1 or --protocol=TCP to force local TCP.
  • Use -S when the required Unix socket path is known.
  • Never place a real password directly after -p in a shared or observable command line.
  • Confirm the mysql> prompt before sending SQL.
  • Leave with QUIT;, q, or Control-D on Unix.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.