How to use Bash to connect to a MySQL database
This page contains instructions for using Bash to connect to a MySQL database on a server. Note that my hosting provider is Bluehost, but I suspect the instructions will work for any host.
Step 1: Log in to your server
First, log in to your server using ssh:
ssh your_username@your_main_domain_name
So if your username was bobknob1 and your main domain name was bobisaknob.com, then you'd type:
ssh bobknob1@bobisaknob.com
You'll then be prompted to enter your password. If you enter it correctly, then you'll be logged in.
Step 2: Perform an operation on a database
To run a query on a database, type:
MySQL -hlocalhost -uUsername -pPassword -D Table_name -e "Query"
Of course, replace Username, Password, Table_name and Query with your details. And note that the username and password here aren't your Bluehost admin login details, but instead the username and password for the database. You can set up a username and password with MySQLDatabases in Bluehost's Cpanel.
Also note that if your password contains special characters like an exclamation mark, then you'll have to escape them by putting a backslash before them. So if your password was password!, you'd have to type password\! instead.
Example
For example, if your username was bobknob1_user, your password was Iamaknob1, your table was called bobknob1_table and your query was "SELECT * FROM Customers", you'd type
MySQL -hlocalhost -ubobknob1_user -pIamaknob1 -D bobknob1_table -e "SELECT * FROM Customers"
Leave a comment