Set Up the Database and Tables
Before creating a trigger, you need a database and the necessary tables. In this step, you will create a database named mydatabase and two tables: products to store product data and product_logs to store audit logs.
First, open the terminal from your desktop.
Connect to the MySQL server as the root user. Since this is a lab environment, you can use sudo to connect without a password.
sudo mysql -u root
Once connected, you will see the MySQL prompt (mysql>).
Now, create the mydatabase database and switch to it. The IF NOT EXISTS clause prevents an error if the database already exists.
CREATE DATABASE IF NOT EXISTS mydatabase;
USE mydatabase;
Next, create the products table. This table will store the ID, name, and price of each product.
CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
price DECIMAL(10, 2) NOT NULL
);
Now, create the product_logs table. This table will store a log of every new product added.
CREATE TABLE product_logs (
log_id INT AUTO_INCREMENT PRIMARY KEY,
product_id INT,
action_description VARCHAR(255),
log_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
You can verify that both tables were created successfully by running:
SHOW TABLES;
You should see the products and product_logs tables listed in the output.
+--------------------+
| Tables_in_mydatabase |
+--------------------+
| product_logs |
| products |
+--------------------+
2 rows in set (0.00 sec)
Now that the database and tables are ready, you can continue to the next step.