DB Practices
DB Practices
AIM:
To create, access, modify and handle the relational databases using DDL, DML and TCL commands.
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:
1
Operation 3: Drop Table
>> DROP TABLE Employee;
OUTPUT:
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:
OUTPUT:
3
Operation 4: Select Data
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.
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.
COMMAND:
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)
);
OUTPUT:
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:
1. Row-Level Trigger
-- Create table
CREATE TABLE employees (
emp_id SERIAL PRIMARY KEY,
name VARCHAR(50),
salary DECIMAL(10, 2)
);
2. Statement-Level Trigger
8
CREATE TRIGGER bulk_update_trigger
AFTER UPDATE ON employees
FOR EACH STATEMENT EXECUTE FUNCTION log_bulk_update();
OUTPUT:
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
cursor = conn.cursor()
cursor.execute("SELECT * FROM employees")
conn.close()
10
OUTPUT:
Example: Python
COMMAND:
import mysql.connector
cursor = conn.cursor()
cursor.execute("SELECT * FROM employees")
conn.close()
OUTPUT:
Example: R
COMMAND:
library(RMySQL)
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 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.
INTRODUCTION:
XML documents can be stored in relational databases as text fields, which allows simple storage without
requiring parsing or structural manipulation.
PROGRAM:
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:
INSERT INTO note (to_name, from_name, heading, body) VALUES ('John', 'Jane', 'Reminder', 'Meeting
tomorrow!');
OUTPUT:
INTRODUCTION:
Data from relational databases can be formatted into XML for portability or external usage.
15
PROGRAM:
SELECT
CONCAT(
'<note><to>', to_name, '</to><from>', from_name, '</from><heading>', heading, '</heading><body>',
body, '</body></note>'
) AS xml_document
FROM note;
OUTPUT:
INTRODUCTION:
Stored XML data can be queried and extracted from relational databases for processing.
PROGRAM:
OUTPUT:
16
3f. XML Querying
INTRODUCTION:
XML querying involves fetching specific elements or attributes from XML documents stored in a
database.
PROGRAM:
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:
18
6. Drop Database:
>> db.dropDatabase()
OUTPUT:
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:
20
OUTPUT:
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:
OUTPUT:
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:
OUTPUT:
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:
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.
PROGRAM:
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)
26
empid INTEGER PRIMARY KEY,
name VARCHAR2(30),
salary NUMBER(10, 2)
)
"""
cursor.execute(create_table_query)
print("Table 'employee' created successfully!")
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