0% found this document useful (0 votes)
9 views27 pages

DB Practices

Uploaded by

abiaravind1525
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views27 pages

DB Practices

Uploaded by

abiaravind1525
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

1.

RELATIONAL DATA MODEL

AIM:

To create, access, modify and handle the relational databases using DDL, DML and TCL commands.

DATA DEFINITION LANGUAGE:

ALGORITHM:
1. Start.
2. Connect to the database using the required credentials.
3. Choose a DDL operation (CREATE, ALTER, DROP, TRUNCATE):
● For CREATE:
a. Specify the name of the object (e.g., table, database).
b. Define its structure (columns, data types, constraints).
c. Execute the CREATE statement.
● For ALTER:
a. Specify the existing object to modify.
b. Define the changes (e.g., add/remove column, modify datatype).
c. Execute the ALTER statement.
● For DROP:
a. Identify the object to delete.
b. Use the DROP command to remove it permanently.
● For TRUNCATE:
a. Specify the table whose data is to be removed.
b. Use the TRUNCATE command to delete all rows (without removing the table).
4. Confirm that the command was executed successfully.
5. Stop.

COMMANDS:

Operation 1: Create Table


>> CREATE TABLE Employee (
emp_id INT PRIMARY KEY,
emp_name VARCHAR(50),
salary DECIMAL(10, 2)
);

Operation 2: Alter Table


>> ALTER TABLE Employee ADD department VARCHAR(50);

1
Operation 3: Drop Table
>> DROP TABLE Employee;

Operation 4: Truncate Table


>> TRUNCATE TABLE Employee;

OUTPUT:

Operation 1: Create Table

Operation 2: Alter Table

Operation 3: Drop Table

Operation 4: Truncate Table

DATA MANIPULATION LANGUAGE:

INTRODUCTION:
1. Start.
2. Connect to the database using the required credentials.
3. Choose a DML operation (INSERT, UPDATE, DELETE, SELECT):
● For INSERT:
a. Identify the table where data will be inserted.
b. Specify the column values to be inserted.
c. Execute the INSERT statement.
● For UPDATE:
a. Identify the table to update.
b. Specify the conditions and the new values.
c. Execute the UPDATE statement.
● For DELETE:
a. Identify the table and the rows to delete.

2
b. Specify the conditions.
c. Execute the DELETE statement.
● For SELECT:
a. Identify the table and columns to retrieve.
b. Specify optional filters (WHERE, ORDER BY).
c. Execute the SELECT query.
4. Review the results or confirm the changes.
5. Stop.

COMMANDS:

Operation 1: Insert Data


>> INSERT INTO Employee (emp_id, emp_name, salary) VALUES (1, 'Alice',
50000);

Operation 2: Update Data


>> UPDATE Employee SET salary = 55000 WHERE emp_id = 1;

Operation 3: Delete Data


>> DELETE FROM Employee WHERE emp_id = 1;

Operation 4: Select Data


>> SELECT * FROM Employee;

OUTPUT:

Operation 1: Insert Data

Operation 2: Update Data

Operation 3: Delete Data

3
Operation 4: Select Data

TRANSACTION CONTROL LANGUAGE:

INTRODUCTION:
1. Start.
2. Connect to the database using the required credentials.
3. Perform one or more DML operations (INSERT, UPDATE, DELETE).
4. Choose a TCL operation (COMMIT, ROLLBACK, SAVEPOINT):
● For COMMIT:
a. Ensure that all required changes have been made.
b. Execute the COMMIT command to save the changes permanently.
● For ROLLBACK:
a. Identify a failed or unwanted operation.
b. Execute the ROLLBACK command to undo changes since the last COMMIT or
SAVEPOINT.
● For SAVEPOINT:
a. Create a savepoint at a specific point in the transaction.
b. Use the savepoint to selectively rollback changes.
5. Confirm the transaction's success or rollback.
6. Stop.

COMMANDS:

Operation 1: Commit
>> COMMIT;

Operation 2: Rollback
>> ROLLBACK;

Operation 3: Savepoint

4
>> SAVEPOINT Save1;

Rollback to Savepoint
>> ROLLBACK TO Save1;

OUTPUT:

Operation 1: Commit

Operation 2: Rollback

Operation 3: Savepoint

Rollback to Savepoint

RESULT:
Thus the database has been connected and data got inserted successfully.

5
2. DISTRIBUTED DATABASES, ACTIVE DATABASES
AND OPEN DATABASE CONNECTIVITY

AIM:

To design and implement distributed databases, utilize triggers for efficient data handling, and access
relational databases programmatically using PHP, Python, and R.

2a. Distributed Database Design and Implementation

INTRODUCTION:

Python can connect to oracle using a python package called cx_Oracle. Oracle is one of the famous and
widely used databases and python’s data processing features are leveraged well using this connectivity.

1. Download and install the relevant version of Oracle.


2. You can test successful installation of cx_Oracle by executing following command on Python shell:
>>> import cx_Oracle >>> \
3. No output confirms successful installation. Otherwise, an error message will be returned.
4. Connect Database Create and Insert operations After successful installation of cx_Oracle, we need to
establish a connection with the Oracle database from the Python program. connect() function helps to
connect to Oracle database from Python and returns the connection object.
5. Connected Database must be closed at the end of the program using close() function.
6. Commit() used to save the changes made in database otherwise the changes will not be reflected in
database.
7. A cursor holds the rows returned by SQL Statement.It helps to traverse over the records returned. Need
a cursor object to do all database operations. Cursor() function is used to create a cursor.

COMMAND:

Database Creation and Partitioning (PostgreSQL Example)

-- Step 1: Create the main database


CREATE DATABASE distributed_db;

-- Step 2: Create tables on different servers (simulated here)


-- On Server 1
CREATE TABLE customers (
customer_id SERIAL PRIMARY KEY,
name VARCHAR(100),
location VARCHAR(100)

6
);

-- On Server 2
CREATE TABLE orders (
order_id SERIAL PRIMARY KEY,
customer_id INT,
product_name VARCHAR(100),
amount DECIMAL(10, 2),
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);

-- Step 3: Configure foreign data wrappers for distributed access


CREATE EXTENSION postgres_fdw;

-- Add the remote server


CREATE SERVER remote_server FOREIGN DATA WRAPPER postgres_fdw
OPTIONS (host 'remote_host', dbname 'remote_db', port '5432');

-- Map the remote table


CREATE FOREIGN TABLE remote_orders (
order_id SERIAL,
customer_id INT,
product_name VARCHAR(100),
amount DECIMAL(10, 2)
) SERVER remote_server OPTIONS (schema_name 'public', table_name 'orders');

OUTPUT:

2b. Row Level and Statement Level Triggers

INTRODUCTION:

● Row-Level Trigger: Executes once for each row affected by a triggering event (e.g., INSERT,
UPDATE, DELETE).
● Statement-Level Trigger: Executes once per triggering event, regardless of the number of rows
affected.

7
COMMAND:

Example: PostgreSQL Triggers

1. Row-Level Trigger

-- Create table
CREATE TABLE employees (
emp_id SERIAL PRIMARY KEY,
name VARCHAR(50),
salary DECIMAL(10, 2)
);

-- Create trigger function


CREATE OR REPLACE FUNCTION log_salary_change() RETURNS TRIGGER AS $$
BEGIN
RAISE NOTICE 'Salary of employee % changed from % to %', OLD.emp_id, OLD.salary,
NEW.salary;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;

-- Attach row-level trigger


CREATE TRIGGER salary_change_trigger
AFTER UPDATE OF salary ON employees
FOR EACH ROW EXECUTE FUNCTION log_salary_change();

2. Statement-Level Trigger

-- Create trigger function


CREATE OR REPLACE FUNCTION log_bulk_update() RETURNS TRIGGER AS $$
BEGIN
RAISE NOTICE 'Bulk update made on employees table';
RETURN NULL;
END;
$$ LANGUAGE plpgsql;

-- Attach statement-level trigger

8
CREATE TRIGGER bulk_update_trigger
AFTER UPDATE ON employees
FOR EACH STATEMENT EXECUTE FUNCTION log_bulk_update();

OUTPUT:

2c. Accessing a Relational Database Using PHP, Python, and R

INTRODUCTION:

Relational databases like MySQL and PostgreSQL can be accessed programmatically using languages
like PHP, Python, and R. These languages provide libraries and frameworks to connect, query, and
manipulate data within relational databases.

Example: PHP

COMMAND:

<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "test_db";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Query database

9
$sql = "SELECT * FROM employees";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["emp_id"]. " - Name: " . $row["name"]. " - Salary: " . $row["salary"]. "<br>";
}
} else {
echo "0 results";
}

$conn->close();
?>

OUTPUT:

Example: Python

COMMAND:

import mysql.connector

# Connect to the database


conn = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="test_db"
)

cursor = conn.cursor()
cursor.execute("SELECT * FROM employees")

for (emp_id, name, salary) in cursor:


print(f"ID: {emp_id}, Name: {name}, Salary: {salary}")

conn.close()

10
OUTPUT:

Example: Python

COMMAND:

import mysql.connector

# Connect to the database


conn = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="test_db"
)

cursor = conn.cursor()
cursor.execute("SELECT * FROM employees")

for (emp_id, name, salary) in cursor:


print(f"ID: {emp_id}, Name: {name}, Salary: {salary}")

conn.close()

OUTPUT:

Example: R

COMMAND:

library(RMySQL)

# Connect to the database


conn <- dbConnect(MySQL(),
dbname = "test_db",

11
host = "localhost",
user = "root",
password = "password")

# Query database
result <- dbGetQuery(conn, "SELECT * FROM employees")

# Display result
print(result)

# Close connection
dbDisconnect(conn)

OUTPUT:

RESULT:

Successfully implemented distributed database design, created and executed row-level and
statement-level triggers, and accessed relational databases programmatically, demonstrating efficient data
handling and query execution.

12
3. XML DATABASES

AIM:

To create, manipulate, and query XML documents using relational databases for storage and extraction,
demonstrating XML integration with database systems.

3a. Creating XML Documents, Document Type Definition (DTD), and XML Schema

INTRODUCTION:

XML (eXtensible Markup Language) is used to store and transport data. DTD and XML Schema define
the structure and data types of XML documents, ensuring consistency.

PROGRAM:

Document:

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE note [
<!ELEMENT note (to, from, heading, body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>
<note>
<to>John</to>
<from>Jane</from>
<heading>Reminder</heading>
<body>Don't forget the meeting tomorrow!</body>
</note>

XML Schema:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>

13
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

OUTPUT:

The XML file and its structure will be validated using the DTD or Schema.

3b. Using a Relational Database to Store XML Documents as Text

INTRODUCTION:

XML documents can be stored in relational databases as text fields, which allows simple storage without
requiring parsing or structural manipulation.

PROGRAM:

SQL Command (MySQL):

CREATE TABLE xml_storage (


id INT AUTO_INCREMENT PRIMARY KEY,
document_text TEXT
);

INSERT INTO xml_storage (document_text) VALUES (


'<?xml version="1.0"
encoding="UTF-8"?><note><to>John</to><from>Jane</from><heading>Reminder</heading><body>
Meeting tomorrow!</body></note>'
);

OUTPUT:

14
3c. Using a Relational Database to Store XML Documents as Data Elements

INTRODUCTION:

XML data can be broken into elements and stored in relational databases, allowing structured queries and
data manipulations.
PROGRAM:

SQL Command (MySQL):

CREATE TABLE note (


id INT AUTO_INCREMENT PRIMARY KEY,
to_name VARCHAR(255),
from_name VARCHAR(255),
heading VARCHAR(255),
body TEXT
);

INSERT INTO note (to_name, from_name, heading, body) VALUES ('John', 'Jane', 'Reminder', 'Meeting
tomorrow!');

OUTPUT:

3d. Creating or Publishing Customized XML Documents from Pre-existing


Relational Databases

INTRODUCTION:

Data from relational databases can be formatted into XML for portability or external usage.

15
PROGRAM:

SQL Command (MySQL):

SELECT
CONCAT(
'<note><to>', to_name, '</to><from>', from_name, '</from><heading>', heading, '</heading><body>',
body, '</body></note>'
) AS xml_document
FROM note;

OUTPUT:

3e. Extracting XML Documents from Relational Databases

INTRODUCTION:

Stored XML data can be queried and extracted from relational databases for processing.

PROGRAM:

SQL Command (MySQL):

SELECT document_text FROM xml_storage WHERE id = 1;

OUTPUT:

16
3f. XML Querying

INTRODUCTION:

XML querying involves fetching specific elements or attributes from XML documents stored in a
database.

PROGRAM:

SQL Command (MySQL):

SELECT ExtractValue(document_text, '/note/to') AS recipient FROM xml_storage WHERE id = 1;

OUTPUT:

RESULT:
The experiment demonstrates the integration of XML with relational databases through creation, storage,
extraction, and querying operations, validating the seamless interaction between structured and
semi-structured data formats.

17
4. NOSQL DATABASES AND BIG DATA
STORAGE SYSTEMS

AIM:

To understand how databases are handled in MongoDB, DynamoDB, Voldemort Key-Value Distributed
Data Store Hbase and Neo4j

MONGODB:

INTRODUCTION:

MongoDB is a NoSQL, open-source document database that is created using C++. It is different from
other Relational Databases like MySQL and is very high-performance in nature. One of the most
important characteristics of NoSQL databases like MongoDB is that they have no schema. That is, unlike
SQL, we do not specify a structure for the tables/databases. MongoDB uses documents and collections
instead of rows and tables like SQL. To create a database using the MongoDB shell MongoDB use
DATABASE_NAME is used to create database. The command will create a new database if it doesn't
exist, otherwise it will return the existing database. Syntax Basic syntax of use DATABASE statement is
as follows − use DATABASE_NAME

COMMANDS:

1. Switch to/Create a Database:


>> use mydb

2. Check the Current Database:


>> db

3. Check List of Databases:


>> show dbs

4. Insert Data into Database (to create it):


>> db.emp.insert({"name":"XXX"})

5. Check the List of Databases Again:


>> show dbs

18
6. Drop Database:
>> db.dropDatabase()

OUTPUT:

1. Switch to/Create a Database:

2. Check the Current Database:

3. Check List of Databases:

4. Insert Data into Database (to create it):

5. Check the List of Databases Again:

6. Drop Database:

19
DYNAMODB:

INTRODUCTION:
DynamoDB is a fully managed NoSQL database service offered by Amazon Web Services (AWS). It
provides fast and predictable performance with seamless scalability. DynamoDB is a key-value and
document database, which means it can store both structured and unstructured data. One of its defining
features is its ability to scale automatically to accommodate large amounts of data and high throughput
requirements.
Unlike traditional relational databases, DynamoDB does not require schema definitions and allows you to
store data in a flexible format. It supports key-value stores and document-style storage, enabling
applications to perform high-speed read and write operations. DynamoDB uses tables, items (equivalent
to rows), and attributes (similar to columns in relational databases) for storing data.
To create a table in DynamoDB, the create-table command is used. This creates a new table with a
specified primary key, and optionally, secondary indexes. DynamoDB also automatically handles
data replication across multiple servers to ensure high availability and durability.
Key Features of DynamoDB:
● Fully managed, scalable, and fast.
● NoSQL database supporting both key-value and document data models.
● Provides features like automatic scaling, backups, and in-memory caching.
● Integrated with AWS services for seamless data operations.

COMMANDS:

1. Create a Table (Equivalent to Database Creation):


>> aws dynamodb create-table --table-name mydb --attribute-definitions
AttributeName=ID,AttributeType=S --key-schema AttributeName=ID,KeyType=HASH
--provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5

2. List Tables (Equivalent to Listing Databases):


>> aws dynamodb list-tables

20
OUTPUT:

1. Create a Table (Equivalent to Database Creation):

2. List Tables (Equivalent to Listing Databases):

VOLDEMORT KEY-VALUE STORE:

INTRODUCTION:
Voldemort is an open-source, distributed key-value store designed to handle large-scale data with high
availability and fault tolerance. It is primarily used for applications that require high scalability and
performance, and it is inspired by Amazon's DynamoDB. Unlike relational databases, Voldemort stores
data as key-value pairs, where each key maps to a value (data), allowing fast retrieval and updates.
Voldemort is designed for horizontal scalability and can handle large volumes of read and write
operations across multiple nodes. It is highly suitable for distributed systems and big data applications.
To create a store in Voldemort, the store create command is used, which sets up a new key-value store
for managing data.

21
Key Features of Voldemort:
● Distributed and highly scalable.
● Data is stored in key-value pairs for efficient access.
● Provides high availability and fault tolerance.
● Supports data replication across multiple nodes to ensure data consistency.

COMMANDS:

1. Create a Store (Equivalent to Database Creation):


>> bin/voldemort-admin store create mydb

2. List Stores (Equivalent to Listing Databases):


>> bin/voldemort-admin store list

3. Drop Store (Equivalent to Drop Database):


>> bin/voldemort-admin store delete mydb

OUTPUT:

1. Create a Store (Equivalent to Database Creation):

2. List Stores (Equivalent to Listing Databases):

3. Drop Store (Equivalent to Drop Database):

HBASE:

INTRODUCTION:
HBase is an open-source, distributed, and scalable column-family-oriented NoSQL database
modeled after Google Bigtable. It is part of the Hadoop ecosystem and is designed to handle

22
large amounts of sparse data across many commodity servers. HBase is suitable for
applications that require low-latency access to large datasets.
Unlike relational databases, HBase does not rely on traditional table and row structures.
Instead, it uses column families to store data in a distributed manner. Data is stored in cells
within these column families, and rows are identified by unique row keys.
HBase is primarily used for applications that need real-time access to large amounts of data,
such as large-scale web analytics, data warehousing, and Internet of Things (IoT) applications.
To create a table in HBase, the create command is used, specifying the table name and the
column family.
Key Features of HBase:
● A column-family NoSQL database for large datasets.
● Part of the Hadoop ecosystem, designed for real-time read/write access.
● Highly scalable, distributed, and fault-tolerant.
● Supports data replication and automatic failover for high availability.

COMMANDS:

1. Create a Table (Equivalent to Database Creation):


>> create 'mydb', 'column_family'

2. List Tables (Equivalent to Listing Databases):


>> list

3. Drop Table (Equivalent to Drop Database):


>> disable 'mydb'
>> drop 'mydb'

OUTPUT:

1. Create a Table (Equivalent to Database Creation):

2. List Tables (Equivalent to Listing Databases):

23
3. Drop Table (Equivalent to Drop Database):

Neo4j:

INTRODUCTION:
Neo4j is an open-source, graph-based NoSQL database that uses a graph structure for storing
and representing data. It is optimized for handling relationships between data entities, which
makes it particularly suitable for use cases like social networks, recommendation systems, fraud
detection, and knowledge graphs.
In Neo4j, data is stored as nodes, relationships, and properties. Nodes represent entities, and
relationships between these entities are first-class citizens in the database. This allows for
efficient querying of interconnected data, which is a key strength of graph databases.
Neo4j uses the Cypher query language to create and manage databases, making it easy to
model and query complex data relationships. To create a database in Neo4j, the CREATE
DATABASE command is used.
Key Features of Neo4j:
● Graph-based NoSQL database for handling interconnected data.
● Uses nodes and relationships to represent and query data.
● Optimized for relationship-heavy queries like social networks and
recommendation engines.
● Supports flexible and intuitive graph modeling using Cypher query language.

COMMANDS:

1. Create a Database:
>> CREATE DATABASE mydb

2. List Databases:
>> SHOW DATABASES

3. Drop Database:
>> DROP DATABASE mydb

24
OUTPUT:

1. Create a Database:

2. List Databases:

3. Drop Database:

RESULT:

Thus the database has been handled using MongoDB, DynamoDB, Voldemort Key-Value Store, Hbase
and Neo4j successfully.

25
5. DATABASE SECURITY

AIM:

To access a Relational Database using Python

ALGORITHM:

Python can connect to oracle using a python package called cx_Oracle. Oracle is one of the famous and
widely used databases and python’s data processing features are leveraged well using this connectivity.

1. Download and install the relevant version of Oracle.


2. You can test successful installation of cx_Oracle by executing following command on Python shell:
>>> import cx_Oracle >>> \
3. No output confirms successful installation. Otherwise, an error message will be returned.
4. Connect Database Create and Insert operations After successful installation of cx_Oracle, we need to
establish a connection with the Oracle database from the Python program. connect() function helps to
connect to Oracle database from Python and returns the connection object.
5. Connected Database must be closed at the end of the program using close() function.
6. Commit() used to save the changes made in database otherwise the changes will not be reflected in
database.
7. A cursor holds the rows returned by SQL Statement.It helps to traverse over the records returned. Need
a cursor object to do all database operations. Cursor() function is used to create a cursor.

PROGRAM:

# Import cx_Oracle module


import cx_Oracle

try:
# Step 4: Connect to the Oracle database
# Syntax: cx_Oracle.connect('username/password@host:port/service_name')
connection = cx_Oracle.connect('tiger/scott@localhost:1521/xe') # Replace with your credentials
print("Connected to Oracle Database:", connection.version)

# Step 7: Create a cursor object


cursor = connection.cursor()

# Step 6: Create a table in the database


create_table_query = """
CREATE TABLE employee (

26
empid INTEGER PRIMARY KEY,
name VARCHAR2(30),
salary NUMBER(10, 2)
)
"""
cursor.execute(create_table_query)
print("Table 'employee' created successfully!")

# Insert data into the table


insert_query = "INSERT INTO employee (empid, name, salary) VALUES (:1, :2, :3)"
rows_to_insert = [
(101, 'John Doe', 50000.00),
(102, 'Jane Smith', 60000.00),
(103, 'Alice Johnson', 70000.00)
]
cursor.executemany(insert_query, rows_to_insert)
print("Data inserted successfully!")

# Step 5: Commit the changes to save them in the database


connection.commit()

except cx_Oracle.DatabaseError as e:
print("Database error occurred:", e)
finally:
# Close the cursor and connection
if 'cursor' in locals() and cursor:
cursor.close()
if 'connection' in locals() and connection:
connection.close()
print("Database connection closed.")

OUTPUT:

RESULT:

Thus the database has been connected and data got inserted successfully.

27

You might also like