III B.
Tech I Semester
FULL STACK DEVELOPMENT – II LAB MANUAL (23A05505)
1. Basics of [Link]
a. Write a React program to implement a counter bu on using react class components
[Link]
import React, { useState } from "react";
const Counter = () => {
// Counter is a state ini alized to 0
const [counter, setCounter] = useState(0);
// Func on is called every me increment bu on is clicked
const handleClick1 = () => {
// Counter state is incremented
setCounter(counter + 1);
};
// Func on is called every me decrement bu on is clicked
const handleClick2 = () => {
// Counter state is decremented
setCounter(counter - 1);
};
return (
<div
style={{
display: "flex",
flexDirec on: "column",
alignItems: "center",
jus fyContent: "center",
fontSize: "300%",
posi on: "absolute",
width: "100%",
height: "100%",
top: "-15%",
}}
>
Counter App
<div
style={{
fontSize: "120%",
posi on: "rela ve",
top: "10vh",
}}
>
{counter}
</div>
<div className="bu ons">
<bu on
style={{
fontSize: "60%",
posi on: "rela ve",
top: "20vh",
marginRight: "5px",
backgroundColor: "green",
borderRadius: "8%",
color: "white",
}}
onClick={handleClick1}
>
Increment
</bu on>
<bu on
style={{
fontSize: "60%",
posi on: "rela ve",
top: "20vh",
marginLe : "5px",
backgroundColor: "red",
borderRadius: "8%",
color: "white",
}}
onClick={handleClick2}
>
Decrement
</bu on>
</div>
</div>
);
};
export default Counter;
Output:
b. Write a React program to implement a counter bu on using react func onal
components
1. [Link]
import React, { useState } from "react";
import CounterBut from "../../components/counterBu on"
const Index = () => {
return (
<CounterBut />
);
};
export default Index;
2. /components/counterBu [Link]
import { useEffect, useState } from "react";
import { useRouter } from "next/router";
func on MyBu on() {
const [count, setCount] = useState(0);
func on handleClick() {
setCount(count + 1);
return (
<div style={{ textAlign:"center", marginTop: "20px"}}
className="py-5">
<bu on onClick={handleClick}
className="bg-dark rounded py-2 px-4 text-white font-
bold"
> I have been clicked {count} mes
</bu on>
</div>
);
}
export default MyBu on;
Output:
c. Write a React program to handle the bu on click events in func onal component
[Link]
import React, { useState } from "react";
const Counter = () => {
return (
<div style={{ textAlign:"center", marginTop: "20px"}} className="py-5">
<bu on onClick={() => alert('Playing!')}>
Play Movie
</bu on>
</div>
);
};
export default Counter;
Output:
1.
2.
d. Write a React program to display text using String literals
[Link]
import React, { useState } from "react";
const Index = () => {
const text = 'One \n Two \n Three \n Four \n Five';
return (
<div style={{ textAlign:"center", marginTop: "20px"}} className="py-5">
<h2>Results: </h2>
{[Link]("\n").map((i,key) => {
return <div key={key}>{i}</div>;
})}
</div>);
};
export default Index;
Output:
2. Important concepts of React. js
a. Write a React program to implement a counter bu on using React use State hook
[Link]
import React, { useState } from "react";
const Index = () => {
const [count, setCount] = useState(0);
return (
<div className="text-center py-5">
<p>You clicked {count} mes</p>
<bu on onClick={() => setCount(count + 1)}>
Click me
</bu on>
</div>);
};
export default Index;
Output:
b. Write a React program to fetch the data from an API using React use Effect hook
[Link]
import React, {useState, useEffect} from 'react';
const Index = () => {
const [userData, setUserData] = useState(null);
useEffect(() => {
fetch('h ps://[Link]/users')
.then(response => [Link]())
.then(data => setUserData(data)); }, []);
return (
<div className="App text-center py-5">
{userData && (
<div>
<h2>User Informa on</h2>
<p>
Name:
{userData[0].name}
</p>
<p>
Email: {userData[0].email}
</p>
{/* Add more user data fields as needed */}
</div>
)}
</div>
);
};
export default Index;
Output:
c. Write a React program with two react components sharing data using Props.
[Link]
import React, {useState, useEffect} from 'react';
const Index = () => {
func on Avatar() {
return (
<img
className="avatar"
src="h p://[Link]/pdf/[Link]"
alt="Lin Lanying"
width={800}
height={400}
/>
);
return (
<div className="App text-center py-5">
<Avatar />
</div>
);
};
export default Index;
Output:
d. Write a React program to implement the forms in react
[Link]
import React, { useState } from "react";
const Index = () => {
const [formData, setFormData] = useState({
name: "",
email: "",
});
const handleChange = (event) => {
const { name, value } = [Link];
setFormData((prevState) => ({ ...prevState, [name]: value }));
};
const handleSubmit = (event) => {
[Link]();
[Link](formData);
};
return (
<div className="text-center py-5">
<form onSubmit={handleSubmit}>
<div className="pt-2">
<label>
Name:
<input
type="text"
name="name"
value={[Link]}
onChange={handleChange}
style={ { marginLe : '10px' }}
/>
</label>
</div>
<div className="pt-3">
<label>
Email:
<input
type="email"
name="email"
value={[Link]}
onChange={handleChange}
style={ { marginLe : '10px' }}
/>
</label>
</div>
<div className="pt-3">
<label>
Address:
<input
type="text"
name="address"
value={[Link]}
onChange={handleChange}
style={ { marginLe : '10px' }}
/>
</label>
</div>
<div className="pt-3">
<label>
City:
<input
type="text"
name="city"
value={[Link]}
onChange={handleChange}
style={ { marginLe : '10px' }}
/>
</label>
</div>
<div className="pt-3">
<label>
State:
<input
type="text"
name="state"
value={[Link]}
onChange={handleChange}
style={ { marginLe : '10px' }}
/>
</label>
</div>
<div className="pt-3">
<label>
Country:
<input
type="text"
name="country"
value={[Link]}
onChange={handleChange}
style={ { marginLe : '10px' }}
/>
</label>
</div>
<div className="pt-3">
<label>
ZipCode:
<input
type="text"
name="zipcode"
value={[Link]}
onChange={handleChange}
style={ { marginLe : '10px' }}
/>
</label>
</div>
<input type="submit" value="Submit" className="mt-3" />
</form>
</div>
);
};
export default Index;
Output:
e. Write a React program to implement the itera ve rendering using map() func on.
[Link]
import React, { useState, useEffect } from "react";
const Index = () => {
const [userData, setUserData] = useState(null);
useEffect(() => {
fetch('h ps://[Link]/users')
.then(response => [Link]())
.then(data => setUserData(data)); }, []);
return(
<div className="App text-center py-5">
{
userData && [Link]((item) => (
<ul style={{ listStyle: 'none'}}>
<li><b>Name</b>: {[Link]}</li>
<li><b>Email</b>: {[Link]}</li>
<li><b>Company</b>: {[Link]}</li>
</ul>
))
</div>
};
export default Index;
Output:
3. Introduc on to Git and GitHub
a. Setup
1. Navigate to the h ps://[Link]/downloads/win and click the download
link for the latest Git version for Windows:
The link contains the latest 64-bit Git version for Windows. Alterna vely, if
you use a 32-bit system, download the 32-bit Git installer.
2. Double-click the downloaded file to extract and launch the installer.
3. Review the GNU General Public License, and when you are ready to install,
click Next.
4. The installer prompts you for an installa on loca on. Leave the default one
unless you want to change it, and click Next.
5. In the component selec on screen, leave the defaults unless you need to
change them and click Next.
6. The installer offers to create a start menu folder. Click Next to accept and
proceed to the next step.
7. Select a text editor you want to use with Git. Use the drop-down menu to
select Notepad++ (or whichever text editor you prefer) and click Next.
8. The next step allows you to choose a different name for your ini al branch.
The default is master. Unless you are working in a team that requires a
different name, leave the default op on and click Next.
9. The next step allows you to change the PATH environment. The PATH is the
default set of directories included when you run a command from the
command line. Keep the middle (recommended) selec on and click Next.
10. The installer prompts you to select the SSH client for Git to use. Git already
comes with its own SSH client, so if you don't need a specific one, leave the
default op on and click Next.
11. The next op on relates to server cer ficates. The default op on is
recommended for most users. If you work in an Ac ve Directory
environment, you may need to switch to Windows Store cer ficates. Select
your preferred op on and click Next.
12. The following selec on configures line-ending conversion, which relates to
the way data is forma ed. The default selec on is recommended for
Windows. Click Next to proceed.
13. Choose the terminal emulator you want to use. The default MinTTY is
recommended for its features. Click Next to con nue.
14. The next step allows you to choose what the git pull command will do. The
default op on is recommended unless you specifically need to change its
behavior. Click Next to con nue with the installa on.
15. The next step is to choose which creden al helper to use. Git uses
creden al helpers to fetch or save creden als. The default op on is the most
stable one. Select your preferred creden al manager and click Next.
16. The next step lets you decide which extra op ons to enable. If you
use symbolic links, which represent shortcuts for the command line, ck the
box. Keep file system caching checked and click Next.
17. Depending on which Git version you are installing, it may offer to install
experimental features. At the me this ar cle was wri en, the installer
offered op ons to include support for pseudo controls and a built-in file
system monitor. For the most stable opera on, do not install experimental
features and click Install.
18. Once the installa on is complete, ck the boxes to view the Release Notes or
launch Git Bash if you want to start using Git right away, and click Finish.
Configure Git (user name, email)
Configure Iden ty
Your iden ty in Git is your username and email address which Git uses
every me you create a commit. To set up your iden ty, open Git Bash and use
the syntax below:
Command Line: git config --global [Link] "[username]"
Replace [user_name] with the actual username you will use. If you have a
GitHub account, you can use that username and email.
Command Line: git config --global [Link] [email]
Create GitHub account and generate a personal access token
1. Clone the Repository
Command Line: git clone h ps://[Link]/username/repository
2. Generate a Personal Access Token (PAT)
o Log in to your GitHub account.
o Go to Se ngs > Developer se ngs > Personal access tokens.
o Click on Generate new token.
o Select the scopes or permissions you need.
o Copy the generated token.
3. Authen cate Using the PAT
o When Git prompts for your password, paste your PAT instead.
o Git will remember the PAT for the dura on of your session.
4. Cache the Creden als
To avoid re-entering your PAT, you can cache your creden als:
Command Line: git config --global creden [Link] cache
5. Approach 2: Using SSH Keys
SSH keys are a more secure and convenient way to log in to Git. Once set up,
SSH keys eliminate the need to enter a username and password for each
opera on.
o Generate SSH Key Pair
Command Line: ssh-keygen -t rsa -b 4096 -C
"your_email@[Link]"
When prompted, press Enter to save the key to the default loca on, or
specify a custom path.
6. Add SSH Key to Your GitHub Account
Navigate to Se ngs > SSH and GPG keys in your GitHub account.
Click on New SSH key, paste the key, and save it.
7. Clone the Repository Using SSH
Command Line: git clone git@[Link]:username/[Link]
b. Basic Git Workflow
1. Open a terminal (or command prompt).
2. Go to your project directory, or create a new directory:
mkdir my-project
cd my-project
3. Ini alize Git in that directory: git init
4. Add files to the repository: git add .
5. Make the first commit: git commit -m "Ini al commit"
6. Set default branch name: git config --global [Link] main
c. Create and add files → git add .
1. Create new files (and folders if needed). For example:
echo "Hello, world!" > fi[Link]
mkdir src
echo "[Link]('hi');" > src/[Link]
2. Check status: git status
You should see these new files listed as untracked. Example output:
Untracked files:
fi[Link]
src/
3. Stage all files (new and modified) by running: git add . (The . means “current
directory and all subdirectories”.)
4. Again check status: git status
Now the files should appear under “Changes to be commi ed”. Example:
Changes to be commi ed:
new file: fi[Link]
new file: src/[Link]
5. Commit: git commit -m "Add ini al files"
d. Commit files → git commit -m "Ini al commit"
git init
# create some files
echo "Hello World" > [Link]
mkdir src
echo "[Link]('Hi');" > src/[Link]
git add .
git status # shows the files are staged (“Changes to be commi ed”)
git commit -m "Ini al commit"
e. Connect to GitHub remote → git remote add origin <repo_url>
Here’s the step-by-step process:
1. Ini alize Git (if not already ini alized):
git init
2. Add your remote repository:
Replace <repo_url> with your actual GitHub repository URL (HTTPS or SSH).
Example (HTTPS):
git remote add origin h ps://[Link]/username/[Link]
Example (SSH):
git remote add origin git@[Link]:username/[Link]
3. Verify the remote was added:
git remote -v
You should see something like:
origin h ps://[Link]/username/[Link] (fetch)
origin h ps://[Link]/username/[Link] (push)
4. Push your code for the first me:
git branch -M main
git push -u origin main
If you already have a remote named origin, you’ll get an error. In that
case, update it with:
git remote set-url origin <repo_url>
Would you like me to also explain the difference between HTTPS vs SSH for
connec ng to GitHub?
f. Push to GitHub → git push -u origin main
Once you’ve connected your local repo to GitHub with
git remote add origin <repo_url>
you can push your local branch to GitHub using:
git push -u origin main
Breakdown:
o git push → pushes commits from your local repo to the remote.
o -u (or --set-upstream) → sets the default upstream branch, so next me
you can simply run git push or git pull without specifying origin main.
o origin → the name of your remote (default is origin).
o main → your branch name (default branch on GitHub is usually main).
From then on, you only need to run:
git push
to push changes, and
git pull
4. Upload React Project to GitHub
1. Create an empty repository on GitHub
1. Sign into your GitHub account.
2. Visit the Create a new repository form.
3. Fill in the form as follows:
a. Repository name: You can enter any name you want*.
* For a project site, you can enter any name you want. For a user site,
GitHub requires that the repository's name have the following
format: {username}.[Link] (e.g. [Link])
The name you enter will show up in a few places: (a) in references to the
repository throughout GitHub, (b) in the URL of the repository, and (c) in the
URL of the deployed React app.
In this tutorial, I'll be deploying the React app as a project site.
I'll enter: react-gh-pages
b. Repository privacy: Select Public (or Private*).
* For GitHub Free users, the only type of repository that can be used with
GitHub Pages is Public. For GitHub Pro users (and other paying users),
both Public and Private repositories can be used with GitHub Pages.
I'll choose: Public
c. Ini alize repository: Leave all checkboxes empty.
That will make it so GitHub creates an empty repository, instead of pre-
popula ng the repository with a [Link], .gi gnore,
and/or LICENSE file.
4. Submit the form.
At this point, your GitHub account contains an empty repository, having the
name and privacy type that you specified.
2. Create a React app
1. Create a React app named my-app:
In case you want to use a different name from my-app (e.g. web-ui), you can
accomplish that by replacing all occurrences of my-app in this tutorial, with
that other name (i.e. my-app --> web-ui).
$ npx create-react-app my-app
That command will create a React app wri en in JavaScript. To create one
wri en in TypeScript, you can issue this command instead:
$ npx create-react-app my-app --template typescript
That command will create a new folder named my-app, which will contain
the source code of a React app.
In addi on to containing the source code of the React app, that folder is also
a Git repository. That characteris c of the folder will come into play in Step
6.
Branch names: master vs. main
The Git repository will have one branch, which will be named either
(a) master, the default for a fresh Git installa on; or (b) the value of the Git
configura on variable, [Link], if your computer is running Git
version 2.28 or later and you have set that variable in your Git configura on
(e.g. via $ git config --global [Link] main).
Since I have not set that variable in my Git installa on, the branch in my
repository will be named master. In case the branch in your repository has a
different name (which you can check by running $ git branch), such as main;
you can replace all occurrences of master throughout the remainder of this
tutorial, with that other name (e.g. master → main).
2. Enter the newly-created folder:
$ cd my-app
At this point, there is a React app on your computer and you are in the folder
that contains its source code. All of the remaining commands shown in this
tutorial can be run from that folder.
3. Install the gh-pages npm package
Install the gh-pages npm package and designate it as a development dependency:
$ npm install gh-pages --save-dev
At this point, the gh-pages npm package is installed on your computer and the React
app's dependence upon it is documented in the React app's [Link] file.
4. Add a homepage property to the [Link] file
Open the [Link] file in a text editor.
$ vi [Link]
In this tutorial, the text editor I'll be using is vi. You can use any text editor you want;
for example, Visual Studio Code.
Add a homepage property in this format*: h ps://{username}.[Link]/{repo-
name}
* For a project site, that's the format. For a user site, the format
is: h ps://{username}.[Link]. You can read more about the homepage property
in the "GitHub Pages" sec on of the create-react-app documenta on.
{
"name": "my-app",
"version": "0.1.0",
+ "homepage": "h ps://[Link]/react-gh-pages",
"private": true,
At this point, the React app's [Link] file includes a property
named homepage.
5. Add deployment scripts to the [Link] file
Open the [Link] file in a text editor (if it isn't already open in one).
$ vi [Link]
Add a predeploy property and a deploy property to the scripts object:
"scripts": {
+ "predeploy": "npm run build",
+ "deploy": "gh-pages -d build",
"start": "react-scripts start",
"build": "react-scripts build",
At this point, the React app's [Link] file includes deployment scripts.
6. Add a "remote" that points to the GitHub repository
Add a "remote" to the local Git repository.
You can do that by issuing a command in this format:
$ git remote add origin h ps://[Link]/{username}/{repo-name}.git
To customize that command for your situa on, replace {username} with your
GitHub username and replace {repo-name} with the name of the GitHub repository
you created in Step 1.
In my case, I'll run:
$ git remote add origin h ps://[Link]/gitname/[Link]
That command tells Git where I want it to push things whenever I—or the gh-
pages npm package ac ng on my behalf—issue the $ git push command from within
this local Git repository.
At this point, the local repository has a "remote" whose URL points to the GitHub
repository you created in Step 1.
7. Push the React app to the GitHub repository
$ npm run deploy
That will cause the predeploy and deploy scripts defined in [Link] to run.
Under the hood, the predeploy script will build a distributable version of the React
app and store it in a folder named build. Then, the deploy script will push the
contents of that folder to a new commit on the gh-pages branch of the GitHub
repository, crea ng that branch if it doesn't already exist.
By default, the new commit on the gh-pages branch will have a commit message of
"Updates". You can specify a custom commit message via the -m op on, like this:
$ npm run deploy -- -m "Deploy React app to GitHub Pages"
8. Configure GitHub Pages
Navigate to the GitHub Pages se ngs page
In your web browser, navigate to the GitHub repository
Above the code browser, click on the tab labeled "Se ngs"
In the sidebar, in the "Code and automa on" sec on, click on "Pages"
Configure the "Build and deployment" se ngs like this:
Source: Deploy from a branch
Branch:
Branch: gh-pages
Folder: / (root)
Click on the "Save" bu on
That's it! The React app has been deployed to GitHub Pages!
9. (Op onal) Store the React app's source code on GitHub
In a previous step, the gh-pages npm package pushed the distributable version of
the React app to a branch named gh-pages in the GitHub repository. However,
the source code of the React app is not yet stored on GitHub.
In this step, I'll show you how you can store the source code of the React app on
GitHub.
Commit the changes you made while you were following this tutorial, to
the master branch of the local Git repository; then, push that branch up to
the master branch of the GitHub repository.
$ git add .
$ git commit -m "Configure React app for deployment to GitHub Pages"
$ git push origin master
5. Introduc on to Node. js and Express. Js
a. Write a program to implement the ‘hello world’ message in the route
through the browser using Express
const express = require('express');
const app = express();
[Link]('/', (req, res) => {
[Link]('<h1> Hello, World! </h1>');
});
[Link](8000, () => {
[Link](`Server is listening at h p://localhost:8000`);
});
Output:
b. Write a program to implement the CRUD opera ons using Express. js
1. Command Line: npm install express
2. Here’s a simple [Link] program that implements CRUD (Create, Read,
Update, Delete) opera ons using an in-memory array (no database).
Code: [Link]
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const PORT = 3000;
// Middleware
[Link]([Link]());
// Dummy data store (in-memory)
let users = [
{ id: 1, name: "Alice", email: "alice@[Link]" },
{ id: 2, name: "Bob", email: "bob@[Link]" },
];
// CREATE → POST /users
[Link]("/users", (req, res) => {
const { name, email } = [Link];
const newUser = { id: [Link] + 1, name, email };
[Link](newUser);
[Link](201).json(newUser);
});
// READ → GET /users
[Link]("/users", (req, res) => {
[Link](users);
});
// READ (single) → GET /users/:id
[Link]("/users/:id", (req, res) => {
const user = users.find(u => [Link] === parseInt([Link]));
if (!user) return [Link](404).json({ message: "User not found" });
[Link](user);
});
// UPDATE → PUT /users/:id
[Link]("/users/:id", (req, res) => {
const user = users.find(u => [Link] === parseInt([Link]));
if (!user) return [Link](404).json({ message: "User not found" });
const { name, email } = [Link];
[Link] = name || [Link];
[Link] = email || [Link];
[Link](user);
});
// DELETE → DELETE /users/:id
[Link]("/users/:id", (req, res) => {
const userIndex = users.findIndex(u => [Link] ===
parseInt([Link]));
if (userIndex === -1) return [Link](404).json({ message: "User not
found" });
const deletedUser = [Link](userIndex, 1);
[Link](deletedUser);
});
// Start server
[Link](PORT, () => {
[Link](` Server running on h p://localhost:${PORT}`);
});
3. How to Run:
1. Ini alize project:
mkdir crud-express && cd crud-express
npm init -y
npm install express body-parser
2. Save the code as [Link].
3. Run: node [Link]
4. Use Postman or cURL to test:
POST h p://localhost:3000/users → Create user
GET h p://localhost:3000/users → Get all users
GET h p://localhost:3000/users/1 → Get user by ID
PUT h p://localhost:3000/users/1 → Update user
DELETE h p://localhost:3000/users/1 → Delete user
c. Write a program to establish the connec on between API and Database using
Express – My SQL driver
1. Install dependencies
mkdir express-mysql-api && cd express-mysql-api
npm init -y
npm install express mysql2 body-parser
2. Create Database and Table in MySQL
CREATE DATABASE mydb;
USE mydb;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);
3. Code: [Link]
const express = require("express");
const bodyParser = require("body-parser");
const mysql = require("mysql2");
const app = express();
const PORT = 3000;
// Middleware
[Link]([Link]());
// Create MySQL Connec on
const db = [Link] on({
host: "localhost",
user: "root", // change if you have a different user
password: "password", // your MySQL password
database: "mydb"
});
// Connect to MySQL
[Link](err => {
if (err) {
[Link](" Database connec on failed: " + [Link]);
return;
}
[Link](" Connected to MySQL as id " + [Link]);
});
// -------------------- CRUD API -------------------- //
// CREATE → POST /users
[Link]("/users", (req, res) => {
const { name, email } = [Link];
[Link](
"INSERT INTO users (name, email) VALUES (?, ?)",
[name, email],
(err, result) => {
if (err) return [Link](500).json({ error: [Link] });
[Link](201).json({ id: [Link], name, email });
}
);
});
// READ → GET /users
[Link]("/users", (req, res) => {
[Link]("SELECT * FROM users", (err, results) => {
if (err) return [Link](500).json({ error: [Link] });
[Link](results);
});
});
// READ (single) → GET /users/:id
[Link]("/users/:id", (req, res) => {
[Link]("SELECT * FROM users WHERE id = ?", [[Link]], (err,
results) => {
if (err) return [Link](500).json({ error: [Link] });
if ([Link] === 0) return [Link](404).json({ message: "User
not found" });
[Link](results[0]);
});
});
// UPDATE → PUT /users/:id
[Link]("/users/:id", (req, res) => {
const { name, email } = [Link];
[Link](
"UPDATE users SET name = ?, email = ? WHERE id = ?",
[name, email, [Link]],
(err, result) => {
if (err) return [Link](500).json({ error: [Link] });
if (result.affectedRows === 0) return [Link](404).json({ message:
"User not found" });
[Link]({ id: [Link], name, email });
}
);
});
// DELETE → DELETE /users/:id
[Link]("/users/:id", (req, res) => {
[Link]("DELETE FROM users WHERE id = ?", [[Link]], (err,
result) => {
if (err) return [Link](500).json({ error: [Link] });
if (result.affectedRows === 0) return [Link](404).json({ message:
"User not found" });
[Link]({ message: "User deleted successfully" });
});
});
// --------------------------------------------------- //
[Link](PORT, () => {
[Link](` Server running on h p://localhost:${PORT}`);
});
6. Introduc on to My SQL
a. Write a program to create a Database and table inside that database using My
SQL Command line client
Step 1: Login to MySQL (mysql -u root -p)
Step 2: Create a Database
CREATE DATABASE company_db;
Verify
SHOW DATABASES;
Step 3: Use the Database
USE company_db;
Step 4: Create a Table
Example: employees table with columns id, name, email, salary.
CREATE TABLE employees (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) UNIQUE,
salary DECIMAL(10,2)
);
Step 5: Verify Table Crea on
SHOW TABLES;
DESCRIBE employees;
Step 6: Insert Some Records (Op onal)
INSERT INTO employees (name, email, salary)
VALUES
('Alice Johnson', 'alice@[Link]', 50000.00),
('Bob Smith', 'bob@[Link]', 60000.00);
Step 7: View Records
SELECT * FROM employees;
Result:
A database company_db is created.
A table employees is created inside it.
Sample data is inserted and displayed.
b. Write a My SQL queries to create table, and insert the data, update the data in
the table
Step 1: Create a Table (Example: a table students with columns id, name,
age, and grade.)
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
age INT,
grade VARCHAR(10)
);
Step 2: Insert Data into the Table
INSERT INTO students (name, age, grade)
VALUES
('Alice', 20, 'A'),
('Bob', 22, 'B'),
('Charlie', 21, 'A'),
('Diana', 23, 'C');
Step 3: Update Data in the Table
UPDATE students
SET grade = 'A'
WHERE name = 'Bob';
c. Write a My SQL program to create the script files in the My SQL workbench
MySQL Script File Example ([Link])
-- =====================================
-- Program: Create Database and Tables
-- Author: Your Name
-- Date: YYYY-MM-DD
-- =====================================
-- Step 1: Create Database
CREATE DATABASE IF NOT EXISTS company_db;
-- Step 2: Select Database
USE company_db;
-- Step 3: Create Table: employees
CREATE TABLE IF NOT EXISTS employees (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) UNIQUE,
salary DECIMAL(10,2),
department VARCHAR(50)
);
-- Step 4: Insert Data
INSERT INTO employees (name, email, salary, department)
VALUES
('Alice Johnson', 'alice@[Link]', 55000.00, 'HR'),
('Bob Smith', 'bob@[Link]', 65000.00, 'IT'),
('Charlie Brown', 'charlie@[Link]', 70000.00,
'Finance');
-- Step 5: Update Data
UPDATE employees
SET salary = 72000.00
WHERE name = 'Charlie Brown';
-- Step 6: Select Data (to verify)
SELECT * FROM employees;
-- Step 7: Delete Example (op onal)
-- DELETE FROM employees WHERE name = 'Bob Smith';
How to Run the Script in MySQL Workbench
1. Open MySQL Workbench.
2. Click on your database connec on.
3. Open a new Query Tab.
4. Copy–paste the script above (or load it from a .sql file: File →
Open SQL Script).
5. Press Execute (lightning icon).