MySQL Selecting a Database
After you connect to the MySQL database, there may be multiple databases you can operate on, so you need to select the database you want to work with.
Select a MySQL database from the command prompt
In the mysql> prompt, you can easily select a specific database.
In MySQL, to select the database to use, you can use the USE statement. The following is the basic syntax:
USE database_name;
Parameter Description:
- database_name is the name of the database you want to select.
After selecting the database, your subsequent SQL queries and operations are performed on the specified database_name database.
Example
The following example selects the database RUNOOB:
[root@host]# mysql -u root -p
Enter password:******
mysql> use RUNOOB;
Database changed
mysql>
After executing the above command, you have successfully selected the RUNOOB database, and all subsequent operations will be performed in the RUNOOB database.
On the command line, you can select a database in the following way:
mysql -u your_username -p -D your_database
- The -D parameter is used to specify the database to select.
For example:
mysql -u root -p -D RUNOOB
After entering the password, you will enter the MySQL prompt, and any subsequent queries and operations will be executed on the RUNOOB database.
Make sure the database you select exists, otherwise you will receive an error message. You can use SHOW DATABASES; to query available databases and ensure the database you want to select is in the list.
Selecting a MySQL database using PHP scripts
PHP provides the function mysqli_select_db to select a database. The function returns TRUE on success, otherwise FALSE.
Syntax
mysqli_select_db(connection,dbname);
| Parameters | Description |
|---|---|
| connection | Required. Specifies the MySQL connection to use. |
| dbname | Required, specifies the default database to use. |
Example
The following example shows how to use the mysqli_select_db function to select a database: