MySQL USE DATABASE
To use a database in MySQL, you need to select it as the active database for your current session. Once a database is selected, all subsequent queries (such as SELECT
, INSERT
, UPDATE
, DELETE
, etc.) will be executed on the tables within that database.
Steps to Use a Database in MySQL
1. Open the MySQL Command-Line Client
First, log in to the MySQL server using the MySQL command-line client or a MySQL GUI tool like MySQL Workbench.
mysql -u username -p
-u username
: Your MySQL username.-p
: Prompts for your password.
2. View Available Databases
To see a list of all available databases on your MySQL server, use:
SHOW DATABASES;
This will display all the databases you have access to.
3. Select the Database You Want to Use
To use a specific database, you need to select it with the USE
statement:
USE database_name;
database_name
: The name of the database you want to use.
For example, if you want to use a database named company_db
, you would execute:
USE company_db;
4. Verify the Current Database
To confirm which database is currently in use, you can run:
SELECT DATABASE();
This will return the name of the database you are currently using.
5. Start Performing Operations on the Database
Once the database is selected, you can perform any operations on it, such as creating tables, inserting data, querying data, etc.
Creating a Table:
CREATE TABLE employees ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100), position VARCHAR(100), salary DECIMAL(10, 2) );
Inserting Data:
INSERT INTO employees (name, position, salary) VALUES ('John Doe', 'Manager', 75000.00);
Querying Data:
SELECT * FROM employees;
Updating Data:
UPDATE employees SET salary = 80000.00 WHERE name = 'John Doe';
Deleting Data:
DELETE FROM employees WHERE name = 'John Doe';
Important Considerations
- Multiple Databases: If you have multiple databases and you want to switch between them, simply use the
USE
command again with the name of the new database. - Privileges: Ensure that your MySQL user has the necessary privileges to perform operations on the selected database.
Example Session
Here's an example of a complete session:
SHOW DATABASES;
-- List all databases
USE company_db;
-- Select the `company_db` database
SELECT DATABASE();
-- Verify that `company_db` is the current database
CREATE TABLE departments (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
location VARCHAR(100)
);
-- Create a new table in the `company_db` database
INSERT INTO departments (name, location)
VALUES ('HR', 'New York'), ('Sales', 'Los Angeles');
-- Insert data into the `departments` table
SELECT * FROM departments;
-- Query data from the `departments` table