Introduction
In this project, you will learn how to print the current time using SQL statements in the MySQL client.
👀 Preview

🎯 Tasks
In this project, you will learn:
- How to access the MySQL database using the
sudocommand - How to write an SQL statement to print the current time in the format
HH:MM:SS - How to use the
ASkeyword to set an alias for the current time - How to save the SQL statement to a file and execute it in the MySQL client
🏆 Achievements
After completing this project, you will be able to:
- Understand how to interact with the MySQL database using SQL statements
- Write SQL queries to retrieve and format date and time data
- Save SQL scripts to files and execute them in the MySQL client
- Apply these skills to build more complex database-driven applications
Access MySQL
In this step, you will learn how to access the MySQL database using the sudo command without any password.
Open a terminal on your system.
Start the MySQL service by running the following command:
sudo service mysql startAccess the MySQL client by running the following command:
sudo mysqlThis will allow you to interact with the MySQL database using SQL statements.
Write the SQL Statement
In this step, you will write an SQL statement to print the current time in the format HH:MM:SS, using the symbols %h %i %S. You will also use the AS keyword to set an alias as Current Time.
In the MySQL client, run the following SQL statement:
SELECT DATE_FORMAT(NOW(), '%h:%i:%S') AS `Current Time`;This statement uses the
DATE_FORMAT()function to format the current time and assigns the result to the aliasCurrent Time.
Save the SQL Statement to a File
In this step, you will save the SQL statement to a file named currentTime.sql in the /home/labex/project directory.
Create the
/home/labex/projectdirectory if it doesn't already exist:sudo mkdir -p /home/labex/projectOpen a text editor and create a new file named
currentTime.sqlin the/home/labex/projectdirectory.Copy and paste the following SQL statement into the file:
SELECT DATE_FORMAT(NOW(), '%h:%i:%S') AS `Current Time`;Save the file.
Run the SQL Script
In this step, you will run the SQL script you created in the previous step to display the current time.
In the MySQL client, run the following command to execute the SQL script:
SOURCE /home/labex/project/currentTime.sql;This will execute the SQL statement in the
currentTime.sqlfile and display the current time in the formatHH:MM:SS.
You should see the following output:
MariaDB [(none)]> SOURCE /home/labex/project/currentTime.sql;
+--------------+
| Current Time |
+--------------+
| 01:44:11 |
+--------------+
1 row in set (0.000 sec)
You have now completed the project of printing the current time using SQL statements in the MySQL client. Congratulations!
Summary
Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.
