MySQL is one of the most popular, free and open-source relational database management system. MySQL powers a wide range of applications from simple blogs to complex enterprise applications.
However, when working in the MySQL CLI on any MySQL client, you need to switch from one database to another. This can quickly become problematic as you can lose track of which database you are currently in, especially in multi-database environment.
Although this may seem like a simple process, it is entirely crucial as it can prevent you from perform actions on the wrong database.
Before proceeding with this tutorial, make sure you have the following:
- MySQL Server
- MySQL Client or MySQL Workbench.
- Basic understanding of SQL
Connect to the MySQL Server
The first step is connecting to the MySQL server. You can do this using any client of your choice. For simplicify, we will use the
mysql CLI interface.
Run the command:
mysql -u username -p
username with your actual username. For example, to login as the
root user, run the command:
mysql -u root -p
Once you run the command above,, you'll be prompted to enter the password for the specified username.
Select a Database
In MySQL, before you can execute any commands on the target database, you need to select it first. You can do this by running the
USEcommand, followed by the name of the database.
The command syntax is as shown:
database_name with the name of your target database.
For example, to switch to the
sakila database, we can run the command:
Show the Current Database
Once you've selected a database, you can check which one is currently in use with the
SELECT DATABASE() function.
The syntax is as shown
Once you run the command above, MySQL will return the name of the currently selected database.
And that's it! You can now easily check which database is currently in use in your MySQL session.
Remember, it's always a good practice to make sure you're in the right database before running any operations, especially those that modify data or schema. The
SELECT DATABASE() function provides an easy way to verify your current database and helps you avoid potential data loss.