UNIT-4 Database Integration

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

UNIT-4

Database Integration
MySQL RDBMS:
What is RDBMS?
RDBMS stands for Relational Database Management System.
RDBMS is a program used to maintain a relational database.
RDBMS is the basis for all modern database systems such as MySQL, Microsoft SQL Server,
Oracle, and Microsoft Access.
RDBMS uses SQL queries to access the data in the database.

What is a Database Table?


A table is a collection of related data entries, and it consists of columns and rows.
A column holds specific information about every record in the table.
A record (or row) is each individual entry that exists in a table.
Look at a selection from the Northwind "Customers" table:
Custome CustomerName ContactNam Address City Postal Countr
rID e Code y

1 Alfreds Maria Anders Obere Str. Berlin 12209 Germa


Futterkiste 57 ny

2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico


Emparedados y Constitución D.F.
helados 2222
The columns in the "Customers" table above are: CustomerID, CustomerName,
ContactName, Address, City, PostalCode and Country. The table has 5 records (rows).
What is a Relational Database?
A relational database defines database relationships in the form of tables. The tables are
related to each other - based on data common to each.
Look at the following three tables "Customers", "Orders", and "Shippers" from the
Northwind database:
What is refential Integrity?
Referential integrity is a term used in database design to describe the relationship between
two tables. It is important because it ensures that all data in a database remains consistent
and up to date. It helps to prevent incorrect records from being added, deleted, or modified.
Customers Table
Custome CustomerNa ContactNam Address City Postal Countr
rID me e Code y

1 Alfreds Maria Obere Str. Berlin 12209 Germa


Futterkiste Anders 57 ny

2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico


Emparedados Constitució D.F.
y helados n 2222
3 Antonio Antonio Mataderos México 05023 Mexico
Moreno Moreno 2312 D.F.
Taquería
The relationship between the "Customers" table and the "Orders" table is the CustomerID
column:

Orders Table
OrderID CustomerID EmployeeID OrderDate ShipperID

10278 5 8 1996-08-12 2

10280 5 2 1996-08-14 1

10308 2 7 1996-09-18 3

10355 4 6 1996-11-15 1
The relationship between the "Orders" table and the "Shippers" table is the ShipperID
column:
Shippers Table
ShipperID ShipperName Phone

1 Speedy (503) 555-


Express 9831

2 United Package (503) 555-


3199

3 Federal (503) 555-


Shipping 9931

Practical-8

Demonstrate Node.js using MySQL to perform the below operations: Create a database,
create a table, insert a record, and update the record.

Step-1. Install Node.js

Step-2. Verify that Node.js was properly installed with the following
Command in CMD: node --version
Step-3. Verify whether NPM (Node Package Manager) is installed or not with the following
command in CMD: npm --version
Step-4. MySQL Installation: download it from https://www.apachefriends.org/index.html

1. Start XAMPP: Open the XAMPP control panel and start the Apache and MySQL services
if they are not already running.
2. Access phpMyAdmin: Open your web browser and go to http://localhost/phpmyadmin/.
This will open phpMyAdmin, a web-based MySQL administration tool that is included
with XAMPP.

Step-5. Create a new folder for your project: Open Visual Studio Code and create a new
folder where you want to store your project files.

Step-6. Open Terminal in Visual Studio Code: Once you have your folder open in Visual
Studio Code, open the integrated terminal. You can do this by selecting Terminal > New
Terminal from the menu bar.

Step-7. Initialize a new Node.js project: In the terminal, navigate to your project folder and
run the following command to initialize a new Node.js project:

npm init -y

Step-8. Install the MySQL package: Install the mysql package using npm by running the
following command in the terminal:

npm install mysql


Step-9. Create a new JavaScript file: Create a new file app.js. This file will contain your
Node.js code.

File name: app.js

// Import required modules


const mysql = require('mysql');

// Create a connection to the MySQL server


const connection = mysql.createConnection({
host: 'localhost', // Change to your MySQL host
user: 'root', // Change to your MySQL username
password: '', // Change to your MySQL password
database: 'my_database' // Change to your MySQL database name
});

// Connect to MySQL server


connection.connect((err) => {
if (err) {
console.error('Error connecting to MySQL server: ' + err.stack);
return;
}
console.log('Connected to MySQL server as ID ' + connection.threadId);
});

// Create a database
connection.query('CREATE DATABASE IF NOT EXISTS my_database', (err, results) => {
if (err) throw err;
console.log('Database created or already exists');
});

// Create a table
connection.query(`CREATE TABLE IF NOT EXISTS my_table (id INT AUTO_INCREMENT
PRIMARY KEY,name VARCHAR(255))`,
(err, results) => {
if (err) throw err;
console.log('Table created or already exists');
});

// Insert a record
connection.query('INSERT INTO my_table (name) VALUES (?)', ['John Doe'], (err, results)
=> {
if (err) throw err;
console.log('Record inserted:', results);
});

// Update a record
connection.query('UPDATE my_table SET name = ? WHERE id = ?', ['Devendra Vashi', 1],
(err, results) => {
if (err) throw err;
console.log('Record updated:', results);
});

// Close the connection


connection.end((err) => {
if (err) {
console.error('Error closing connection: ' + err.stack);
return;
}
console.log('Connection closed');
});

Step-10. Modify the MySQL connection details: Modify the MySQL connection details in the
code to match your MySQL server configuration. Update the host, user, password, and
database properties in the createConnection function call.
Step-11. Run the script: Save your app.js file and return to the terminal in Visual Studio
Code. Run the script by executing the following command:
node app.js

Step-12. Verify the output: Check the output in the terminal to see if the script executed
successfully. You should see messages indicating the connection status, database creation,
table creation, record insertion, record update, and the closure of the connection.

Practical-9

Demonstrate Node.js using MySQL to perform the below operations using the user-
defined function: delete record, select record, select unique, drop table.

Step-1. Install Node.js

Step-2. Verify that Node.js was properly installed with the following
Command in CMD: node --version

Step-3. Verify whether NPM (Node Package Manager) is installed or not with the following
command in CMD: npm --version

Step-4. MySQL Installation: download it from https://www.apachefriends.org/index.html


1. Start XAMPP: Open the XAMPP control panel and start the Apache and MySQL services
if they are not already running.
2. Access phpMyAdmin: Open your web browser and go to http://localhost/phpmyadmin/.
This will open phpMyAdmin, a web-based MySQL administration tool that is included
with XAMPP.

Step-5. Create a new folder for your project: Open Visual Studio Code and create a new
folder where you want to store your project files.

Step-6. Open Terminal in Visual Studio Code: Once you have your folder open in Visual
Studio Code, open the integrated terminal. You can do this by selecting Terminal > New
Terminal from the menu bar.

Step-7. Initialize a new Node.js project: In the terminal, navigate to your project folder and
run the following command to initialize a new Node.js project:

npm init -y

Step-8. Install the MySQL package: Install the mysql package using npm by running the
following command in the terminal:

npm install mysql


Step-9. Create a new JavaScript file: Create a new file app.js. This file will contain your
Node.js code.

File name: app.js

// Import required modules


const mysql = require('mysql');

// Create a connection to the MySQL server


const connection = mysql.createConnection({
host: 'localhost', // Change to your MySQL host
user: 'root', // Change to your MySQL username
password: '', // Change to your MySQL password
database: 'my_database' // Change to your MySQL database name
});

// Connect to MySQL server


connection.connect((err) => {
if (err) {
console.error('Error connecting to MySQL server: ' + err.stack);
return;
}
console.log('Connected to MySQL server as ID ' + connection.threadId);
});

// Delete record
const deleteRecord = (id) => {
const query = `DELETE FROM my_table WHERE id = ?`;
connection.query(query, [id], (err, results) => {
if (err) {
console.error('Error deleting record: ' + err.stack);
return;
}
console.log('Record deleted successfully.');
});
};

// Select record
const selectRecord = (id) => {
const query = `SELECT * FROM my_table WHERE id = ?`;
connection.query(query, [id], (err, results) => {
if (err) {
console.error('Error selecting record: ' + err.stack);
return;
}
console.log('Selected record:', results[0]);
});
};

// Select unique records


const selectUniqueRecords = () => {
const query = `SELECT DISTINCT name FROM my_table`;
connection.query(query, (err, results) => {
if (err) {
console.error('Error selecting unique records: ' + err.stack);
return;
}
console.log('Unique records:', results);
});
};

// Drop table
const dropTable = () => {
//create my_table first under my_database first
const query = `DROP TABLE my_table1`;
connection.query(query, (err, results) => {
if (err) {
console.error('Error dropping table: ' + err.stack);
return;
}
console.log('Table dropped successfully.');
});
};

// Delete a record
deleteRecord(1);

// Select a record
selectRecord(1);

// Select unique records


selectUniqueRecords();

// Drop table
dropTable();

Step-10. Modify the MySQL connection details: Modify the MySQL connection details in the
code to match your MySQL server configuration. Update the host, user, password, and
database properties in the createConnection function call.
Step-11. Run the script: Save your app.js file and return to the terminal in Visual Studio
Code. Run the script by executing the following command:

node app.js

Step-12. Verify the output: Check the output in the terminal to see if the script executed
successfully.
Introduction to NoSQL(Not Only SQL database):

NoSQL is an approach to database management that can accommodate a wide variety of


data models, including key-value, document, columnar and graph formats. A NoSQL
database generally means it is non-relational, distributed, flexible and scalable.
1. Flexible Data Models: Unlike RDBMS, which enforce a rigid schema and
require data to be structured in tables with predefined columns and
relationships, NoSQL databases support various data models, including key-
value stores, document stores, column-family stores, and graph databases.

This flexibility allows developers to choose the most appropriate data model
for their specific use case.
2. Scalability: NoSQL databases are designed to scale horizontally, meaning
they can handle large amounts of data and high read/write throughput by
adding more servers to a distributed architecture.

This horizontal scaling contrasts with the vertical scaling approach often used
in traditional RDBMS, where you upgrade the hardware of a single server
to handle increased load.
3. High Availability and Fault Tolerance: Many NoSQL databases are built
with features for high availability and fault tolerance. They often use
replication and sharding techniques (distributes data across multiple servers)
to ensure that data remains available even if individual nodes fail. This is
crucial for applications requiring continuous uptime and reliability.
4. Performance Optimization: NoSQL databases are optimized for specific use
cases, allowing for high-performance data access and retrieval. For example,
document-oriented databases are well-suited for applications with
hierarchical data structures, such as JSON or XML documents, while key-
value stores excel in scenarios requiring fast reads and writes with simple
data structures.
5. Schema Flexibility: NoSQL databases typically offer schema flexibility,
allowing developers to store data without a predefined schema or to alter the
schema without disrupting the application. This agility is particularly
beneficial in agile development environments where requirements may
change frequently.
6. Consistency Models: NoSQL databases often relax the traditional ACID
(Atomicity, Consistency, Isolation, Durability) properties of RDBMS in favor of
BASE (Basically Available, Soft state, Eventually consistent) consistency
models. This trade-off prioritizes availability and partition tolerance over strict
consistency, making NoSQL databases suitable for distributed systems and
big data applications where eventual consistency is acceptable.
7. Use Cases: NoSQL databases are commonly used in web applications, real-
time analytics, content management systems, IoT (Internet of Things)
platforms, and other scenarios where traditional RDBMS may struggle to
handle large volumes of unstructured or semi-structured data efficiently.

Examples of popular NoSQL databases include MongoDB (document store), Apache


Cassandra (column-family store), Redis (key-value store), and Neo4j (graph
database).

In summary, NoSQL databases provide a scalable, flexible, and high-performance


alternative to traditional relational databases, catering to the needs of modern
applications dealing with massive amounts of data and demanding performance
requirements. However, it's essential to choose the right NoSQL database based on
the specific requirements and characteristics of your application.

Types of NoSQL database:

NoSQL databases can be categorized into several types based on their data models
and storage architectures. Here are explanations of some of the most common types
of NoSQL databases:

1. Key-Value Stores:
• Explanation: Key-value stores are the simplest form of NoSQL
databases, where each item in the database is stored as a key-value
pair. They are highly efficient for read and write operations, making
them suitable for caching and session management.
• Examples: Redis, Amazon DynamoDB, Riak
2. Document Stores:
• Explanation: Document stores store data in flexible, semi-structured
documents, typically using formats like JSON or XML. Documents can
vary in structure within the same collection, offering schema flexibility
and easy horizontal scalability.
• Examples: MongoDB, Couchbase, CouchDB
3. Column-Family Stores (Wide-Column Stores):
• Explanation: Column-family stores organize data into columns rather
than rows, making them efficient for querying large datasets and
aggregating data across different columns. They are well-suited for use
cases requiring high availability and scalability.
• Examples: Apache Cassandra, Apache HBase, ScyllaDB
4. Graph Databases:
• Explanation: Graph databases are designed to represent and query
relationships between data entities. They use nodes, edges, and
properties to model complex relationships, making them ideal for
applications such as social networks, recommendation engines, and
fraud detection.
• Examples: Neo4j, Amazon Neptune, ArangoDB
5. Time-Series Databases:
• Explanation: Time-series databases are optimized for storing and
querying time-stamped data points, such as sensor readings, stock
prices, or system metrics. They offer efficient storage and retrieval of
time-series data for analytics and monitoring purposes.
• Examples: InfluxDB, Prometheus, TimescaleDB
6. Object Stores:
• Explanation: Object stores provide a distributed storage infrastructure
for managing unstructured data as objects. They are commonly used
for storing large binary objects, such as images, videos, and backups,
in a scalable and cost-effective manner.
• Examples: Amazon S3, Google Cloud Storage, MinIO
7. NewSQL Databases:
• Explanation: NewSQL databases combine elements of traditional SQL
databases with the scalability and flexibility of NoSQL databases. They
aim to provide distributed transactions, ACID compliance, and
relational query capabilities while supporting horizontal scalability.
• Examples: CockroachDB, Google Spanner, NuoDB

Each type of NoSQL database has its strengths and weaknesses, and the choice
depends on the specific requirements of the application, including data structure,
scalability needs, consistency requirements, and performance goals.

You might also like