MySQL Use Database
In this article, we explained how to select a database in MySQL and how to view the current database.
In a MySQL Database server, there may be multiple databases. If you want to perform operations such as queries, you should select a database to be operated on first. You can use the USE statement to select or switch databases.
MySQL USE syntax
To select a database as the default database, please use the USE statement as follow:
USE database_name;
The database_name is name of a the database which you want to select.
If success, MySQL will give you a response as following:
Database changedIf you specified a database name that is not existing, MySQL will give you an error like the following:
ERROR 1049 (42000): Unknown database 'db1'MySQL USE database Example
Open mysql client and follow the steps below to select the database to operate on.
-
Log in to the MySQL server:
mysql -u root -pPlease follow the prompts to enter the password for the
rootaccount.At this time, the database has not been selected, and you cannot perform query, insert, etc. operations. For example, if you try to view all the tables, an error will be returned.
SHOW tables;ERROR 1046 (3D000): No database selected -
Choose
testdbDatabase.USE testdb;Database changedNow the default database is
testdb. -
Switch to
sakilaDatabase.USE sakila;Database changedAt this point, the default database has been switched from
testdbtosakila.
Specify the database when logging in
You can directly specify the database you want to operate when you log in to the MySQL server. Please use the following command:
mysql -u root -p -D testdb
Here, we use the -D testdb parameter to specify the database which database we want to connect to.
View current database
If you want to get the database currently use, please use the following 3 methods:
-
Using
DATABASE()orSCHEMA()function:SELECT DATABASE();+------------+ | DATABASE() | +------------+ | testdb | +------------+ 1 row in set (0.00 sec) -
Using
STATUSstatement in mysql client:STATUS-------------- mysql Ver 8.0.26-0ubuntu0.20.04.2 for Linux on x86_64 ((Ubuntu)) Connection id: 550 Current database: testdb ... -
Using
SHOW TABLESstatement in mysql client:SHOW TABLES;+------------------+ | Tables_in_testdb | +------------------+ | order_item | | user | +------------------+ 2 rows in set (0.00 sec)In the output, the header
Tables_in_testdbtells us that the current database istestdb.
Conclusion
In this article, we learned to select a database using the USE statement and several ways to get the current database.