Engineering · 1 min read
The MySQL CLI: Remote Connection and Flags
Connect to a remote MySQL through a local proxy port, with the flag table: -h host, -P port (capital), -p password (glued, no space), -u user, -D database, -e execute.
Connect to a remote MySQL through a local port (e.g. a Cloud SQL proxy tunnel):
mysql -h 127.0.0.1 -P 20001 -u "$USERNAME" -p"$PASSWORD" -D app_production \
-e "SELECT a.asset_id FROM asset AS a WHERE uploaded_package_id = 100"
| Flag | Long form | Meaning |
|---|---|---|
-h | --host | Host to connect to. 127.0.0.1 = the local end of a proxy tunnel, not the cloud DB directly. |
-P | --port | TCP port (default 3306). Capital P, lowercase -p is password. |
-u | --user | MySQL account username. |
-p | --password | Password. No space after -p (-pSECRET); -p alone → interactive prompt. |
-D | --database | Default schema, so asset works instead of app_production.asset. |
-e | --execute | Run the SQL non-interactively, print the result, exit. |
-p passwith a space is parsed as “prompt for the password, then usepassas the database name.” Always glue it:-p"$PASSWORD".- A password on the CLI is visible in
psand warns as insecure; for scripts prefer--defaults-extra-file.
From this session: queried prod app_production.asset for uploaded_package_id = 100 via the cloud-sql-proxy tunnel on 127.0.0.1:20001.
-Pis port,-pis the glued-on password: those two casings bite most; get them right and you won’t turn your password into a database name.
References
- MySQL connecting: https://dev.mysql.com/doc/refman/8.0/en/connecting.html
- MySQL command-line options: https://dev.mysql.com/doc/refman/8.0/en/command-line-options.html
Related: back to the remote DB overview; these flags are the five coordinates and the connection URI taken apart. Next: four ways to feed inline SQL.