To log in to a MySQL database and execute queries from the Linux terminal, follow these steps:
1. Open the terminal
First, open your Linux terminal.
2. Log in using the MySQL client
In the terminal, you can log in to the MySQL database using the mysql command with the necessary parameters. The basic command format is as follows:
bashmysql -u username -p
Here, -u is followed by your MySQL username, and -p indicates that the command will prompt you for your password. For example, if your username is root, you can enter:
bashmysql -u root -p
After entering the command, the system will prompt you for your password. After entering the correct password, you will be logged into the MySQL server.
3. Select the database
After logging in, you can use the USE command to select the database you want to query. For example, if the database name is testdb, you can enter:
sqlUSE testdb;
4. Execute the query
Once the database is selected, you can execute SQL queries. For example, if you want to view all records in the employees table, you can use the following command:
sqlSELECT * FROM employees;
5. Exit MySQL
After completing the query, you can exit the MySQL client by entering the exit command:
bashexit
Example
Suppose I have a database named school with a table named students. I want to log in to MySQL from the Linux command line and view all student information. Here are my steps:
- Open the terminal.
- Enter
mysql -u root -p, then enter your password. - Enter
USE school;to select the database. - Execute the query
SELECT * FROM students;to view all student data. - After completion, enter
exitto exit the MySQL session.
Through this process, you can successfully log in to MySQL from the Linux terminal and query the database. This method is very useful for database administrators and developers when managing and debugging databases.