5.
Introduction to MySQL
a. Installation and Create Database and Table using MySQL Command
Line Client
Installation (Windows example):
1. Download the MySQL Installer from the official site or other trusted sources.
2. Run the installer and select a "Typical" setup to install MySQL Server and Command
Line Client.
3. Configure the root password during setup.
4. Add the MySQL bin directory to your system PATH for easy command-line access.
Connect to MySQL via Command Line Client:
mysql -u root -p
(Enter the root password when prompted.)
Create a Database and Table:
CREATE DATABASE SampleDB;
USE SampleDB;
CREATE TABLE Employees (
ID INT PRIMARY KEY AUTO_INCREMENT,
Name VARCHAR(100),
Position VARCHAR(50),
Salary DECIMAL(10, 2)
);
Output: Database and table created successfully. You will see "Query OK" messages.
b. Queries to Create Table, Insert Data, and Update Data
Create Table (if not created earlier):
CREATE TABLE Departments (
DeptID INT PRIMARY KEY,
DeptName VARCHAR(100)
);
Insert Data:
INSERT INTO Employees (Name, Position, Salary) VALUES ('Alice', 'Manager', 75000);
INSERT INTO Employees (Name, Position, Salary) VALUES ('Bob', 'Developer', 55000);
Update Data:
UPDATE Employees SET Salary = 60000 WHERE Name = 'Bob';
Output: Messages like "Query OK, 1 row affected" confirm operations.
c. Implementing Subqueries
Example: Select employees who earn more than the average salary
SELECT Name, Salary FROM Employees
WHERE Salary > (SELECT AVG(Salary) FROM Employees);
Example: Find departments with no employees (assuming Employees
table has DeptID foreign key)
SELECT DeptName FROM Departments
WHERE DeptID NOT IN (SELECT DeptID FROM Employees);
Output: Query results will show matching rows per the subqueries.
d. Creating Script Files in MySQL Workbench
1. Open MySQL Workbench and connect to your MySQL server.
2. Open a new SQL Editor tab.
3. Write your SQL commands (e.g., CREATE DATABASE, CREATE TABLE, INSERT).
4. Use File > Save Script As to save your commands as a .sql script file.
5. You can later run this script using Workbench or command line:
prompt @$f
@)mysqldump -u root -p testdb > C:\users\hp\[Link]
e. Create Database Directory and Initialize [Link] File for API
Integration
Steps:
1. In your project directory (e.g., a [Link] or Java project), create a folder named
database or similar.
2. Inside this folder, create a file [Link] with your SQL initialization commands:
CREATE DATABASE IF NOT EXISTS SampleDB;
USE SampleDB;
CREATE TABLE Employees (
ID INT PRIMARY KEY AUTO_INCREMENT,
Name VARCHAR(100),
Position VARCHAR(50),
Salary DECIMAL(10,2)
);
INSERT INTO Employees (Name, Position, Salary) VALUES ('Alice', 'Manager', 75000);
3. In your API code (e.g., using [Link] with mysql package), you connect to the
database specifying the database name (SampleDB). The API then uses this
database and its tables for operations.