0% found this document useful (0 votes)
3 views19 pages

Dbms Code & Viva

The document outlines a series of SQL and Python code examples for creating and managing databases, including operations such as creating tables, inserting data, updating records, and creating views. It also includes VIVA questions and answers related to database concepts, real-time applications, and the use of MySQL with Python. Additionally, it covers various applications like property management and hotel management systems, emphasizing the importance of security and data integrity.

Uploaded by

Deshma
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)
3 views19 pages

Dbms Code & Viva

The document outlines a series of SQL and Python code examples for creating and managing databases, including operations such as creating tables, inserting data, updating records, and creating views. It also includes VIVA questions and answers related to database concepts, real-time applications, and the use of MySQL with Python. Additionally, it covers various applications like property management and hotel management systems, emphasizing the importance of security and data integrity.

Uploaded by

Deshma
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/ 19

EXP 12

-- 1. Create Database
CREATE DATABASE IF NOT EXISTS lab_views_demo;

-- 2. Use Database
USE lab_views_demo;

-- 4. Create Table 1: Student


CREATE TABLE Student (
student_id INT PRIMARY KEY,
name VARCHAR(50),
department VARCHAR(50),
marks INT
);

-- 5. Insert Data into Student


INSERT INTO Student VALUES
(1, 'Ravi', 'CSE', 88),
(2, 'Anu', 'IT', 76),
(3, 'Kumar', 'ECE', 90),
(4, 'Latha', 'CSE', 45);

-- 6. Create View on Student (view with students scoring above 75)


CREATE VIEW HighScorers AS
SELECT student_id, name, marks
FROM Student
WHERE marks > 75;

-- 7. Update through view (actually update base table)


UPDATE Student SET marks = 80 WHERE name = 'Latha';

-- 8. Display the updated view data


SELECT * FROM HighScorers;

-- 9. Create Table 2: Department


CREATE TABLE Department (
dept_id INT PRIMARY KEY,
dept_name VARCHAR(50),
hod VARCHAR(50)
);

-- 10. Insert Data into Department


INSERT INTO Department VALUES
(101, 'CSE', 'Dr. Ram'),
(102, 'IT', 'Dr. Meena'),
(103, 'ECE', 'Dr. Ravi');

-- 11. Create View on Department (shows dept_name and hod)


CREATE VIEW DepartmentView AS
SELECT dept_name, hod
FROM Department;

-- 12. Update through Department base table (change hod of CSE)


UPDATE Department SET hod = 'Dr. Priya' WHERE dept_name = 'CSE';

-- 13. Display the updated DepartmentView


SELECT * FROM DepartmentView;

-- 14. Create Table 3: Course


CREATE TABLE Course (
course_id INT PRIMARY KEY,
course_name VARCHAR(50),
dept_name VARCHAR(50)
);

-- 15. Insert Data into Course


INSERT INTO Course VALUES
(1, 'DBMS', 'CSE'),
(2, 'Networking', 'ECE'),
(3, 'Web Development', 'IT');

-- 16. Create View on Course (courses offered by CSE dept)


CREATE VIEW CourseView AS
SELECT course_id, course_name
FROM Course
WHERE dept_name = 'CSE';

-- 17. Update course name in Course table


UPDATE Course SET course_name = 'Advanced DBMS' WHERE course_id = 1;

-- 18. Display the updated CourseView


SELECT * FROM CourseView;

-- 19. Drop all views


DROP VIEW IF EXISTS HighScorers;
DROP VIEW IF EXISTS DepartmentView;
DROP VIEW IF EXISTS CourseView;
VIVA 12

VIVA QUESTIONS & ANSWERS:

1.​ Three real-time applications of views?​

○​ Reporting dashboards, user-role access control, simplifying joins.​

2.​ Can you update data through a view?​

○​ Yes, if the view is based on a single table without GROUP BY or joins.​

3.​ How are views stored in MySQL?​

○​ Views are stored as SQL query definitions, not as physical data.​

4.​ What is the benefit of using views?​

○​ Data abstraction, security, and simplified query handling.​

5.​ How do you delete a view in MySQL?​

○​ Using DROP VIEW view_name;​

EXP: 13

CREATE DATABASE xmlschema_demo;


USE xmlschema_demo;

CREATE TABLE books (


id INT,
title VARCHAR(100),
author VARCHAR(100),
price DECIMAL(10,2)
);

SHOW VARIABLES LIKE 'secure_file_priv';


LOAD XML INFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/books.xml'
INTO TABLE books
ROWS IDENTIFIED BY '<book>';
INSERT INTO books (id, title, author, price) VALUES
(201, 'Clean Code', 'Robert C. Martin', 450.00),
(202, 'The Pragmatic Programmer', 'Andrew Hunt', 520.00),
(203, 'Introduction to Algorithms', 'Cormen et al.', 980.50),
(204, 'You Don''t Know JS', 'Kyle Simpson', 375.00),
(205, 'Database Management Systems', 'Raghu Ramakrishnan', 610.75);
SELECT * FROM books;
SELECT title, author FROM books;

SELECT * FROM books WHERE price > 500;

📌 VIVA QUESTIONS (with crisp answers):


1.​ Write any three real-time applications used with XML Schema?​
➤ Web APIs (SOAP), Office file formats, and Database exchange formats.​

2.​ Why is XML Schema preferred over DTD?​


➤ XSD supports datatypes, constraints, and namespaces, which DTD does
not.​

3.​ How do you validate an XML file against a schema?​


➤ Using XML tools or parsers like Xerces, Altova, or online validators.​

4.​ What is the role of namespaces in XML Schema?​


➤ They avoid naming conflicts in complex XML documents.​

5.​ How can XML Schema improve data exchange?​


➤ By enforcing structure and datatypes, it ensures consistent, valid data
across systems.

EXP: 14

CREATE TABLE students (


id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
dept VARCHAR(50),
year INT,
gpa DECIMAL(3,1)
);
INSERT INTO students (name, dept, year, gpa)
VALUES ('Arun', 'IT', 3, 8.1);
INSERT INTO students (name, dept, year, gpa) VALUES
('Divya', 'CSE', 2, 9.0),
('Ravi', 'ECE', 4, 7.5),
('Meena', 'EEE', 1, 8.6),
('Karan', 'MECH', 3, 8.0);
SELECT * FROM students;
SELECT * FROM students WHERE name = 'Ravi';
SELECT * FROM students WHERE gpa > 8.0;
SELECT * FROM students WHERE dept = 'IT';

1. Write any three real-time applications used with NoSQL?​


➡ Facebook (for messaging), Netflix (for content delivery), and Uber (for ride data
tracking).

2. Name some popular NoSQL databases.​


➡ MongoDB, Cassandra, CouchDB, and Redis.

3. How is data stored in NoSQL databases?​


➡ As flexible documents (JSON/BSON), key-value pairs, column families, or
graphs—depending on the type.

4. What are the advantages of NoSQL databases over SQL databases?​


➡ High scalability, flexible schemas, faster performance for large unstructured data,
and easier horizontal scaling.

5. How do you ensure data consistency in NoSQL databases?​


➡ Using techniques like replication, quorum reads/writes, and consistency models
like eventual consistency or strong consistency depending on the database.

EXP:15

SQL CODE

CREATE DATABASE IF NOT EXISTS studentdb;


USE studentdb;
CREATE TABLE IF NOT EXISTS books (
id INT PRIMARY KEY,
title VARCHAR(100),
author VARCHAR(100),
price FLOAT
);
SELECT * FROM studentdb.books;
PYTHON:

import tkinter as tk
from tkinter import messagebox
import mysql.connector

# Connect to MySQL
conn = mysql.connector.connect(
host='localhost',
user='root',
password='', # Replace with your MySQL password
database='studentdb'
)
cursor = conn.cursor()

# GUI setup
root = tk.Tk()
root.title("Simple GUI Database App")

# Labels and input fields


tk.Label(root, text="Book ID").grid(row=0, column=0)
tk.Label(root, text="Title").grid(row=1, column=0)
tk.Label(root, text="Author").grid(row=2, column=0)
tk.Label(root, text="Price").grid(row=3, column=0)

id_entry = tk.Entry(root)
title_entry = tk.Entry(root)
author_entry = tk.Entry(root)
price_entry = tk.Entry(root)

id_entry.grid(row=0, column=1)
title_entry.grid(row=1, column=1)
author_entry.grid(row=2, column=1)
price_entry.grid(row=3, column=1)

# Insert data function


def insert_data():
try:
book_id = int(id_entry.get())
title = title_entry.get()
author = author_entry.get()
price = float(price_entry.get())
cursor.execute("INSERT INTO books (id, title, author,
price) VALUES (%s, %s, %s, %s)",
(book_id, title, author, price))
conn.commit()
messagebox.showinfo("Success", "Record inserted
successfully")
# Clear entries
id_entry.delete(0, tk.END)
title_entry.delete(0, tk.END)
author_entry.delete(0, tk.END)
price_entry.delete(0, tk.END)
except Exception as e:
messagebox.showerror("Error", str(e))

# Insert Button
insert_btn = tk.Button(root, text="Insert Book",
command=insert_data)
insert_btn.grid(row=4, column=0, columnspan=2)

root.mainloop()

cursor.close()
conn.close()

VIVA QUESTIONS (Short & Sweet)

1.​ 3 Real-time GUI DB apps?​


Banking apps, Inventory systems, Student management.​

2.​ Tools used for GUI DB apps?​


Tkinter, PyQt, MySQL, SQLite, JavaFX.​
3.​ Role of database?​
Store and manage persistent data.​

4.​ How does GUI interact?​


GUI sends SQL queries via connectors like mysql.connector.​

5.​ Advantages?​
Easy interaction, less coding for users, error handling visually.​

EXP:16

CREATE DATABASE IF NOT EXISTS property_db;

USE property_db;

CREATE TABLE IF NOT EXISTS shops (


shop_id INT PRIMARY KEY,
shop_name VARCHAR(100),
floor INT,
area FLOAT
);

PYTHON

import mysql.connector

# Connect to MySQL
con = mysql.connector.connect(
host="localhost",
user="root",
password="", database="property_db"
)

✅ Database Connected Successfully")


cursor = con.cursor()
print("

while True:
print("\n--- Property Management Menu ---")
print("1. Insert Shop Details")
print("2. Update Shop")
print("3. Delete Shop")
print("4. Display All Shops")
print("5. Exit")

ch = int(input("Enter your choice: "))

if ch == 1:
n = int(input("Enter number of shops to add: "))
for _ in range(n):
shop_id = int(input("Enter Shop ID: "))
name = input("Enter Shop Name: ")
floor = int(input("Enter Floor: "))
area = float(input("Enter Area (in sq.ft): "))

query = "INSERT INTO shops (shop_id, shop_name,


floor, area) VALUES (%s, %s, %s, %s)"
values = (shop_id, name, floor, area)
cursor.execute(query, values)

✅ Shop(s) added successfully!")


con.commit()
print("

elif ch == 2:
shop_id = int(input("Enter Shop ID to update: "))
name = input("Enter New Shop Name: ")
floor = int(input("Enter New Floor: "))
area = float(input("Enter New Area: "))

query = "UPDATE shops SET shop_name=%s, floor=%s,


area=%s WHERE shop_id=%s"
values = (name, floor, area, shop_id)
cursor.execute(query, values)

✅ Shop updated successfully!")


con.commit()
print("

elif ch == 3:
name = input("Enter Shop Name to delete: ")
query = "DELETE FROM shops WHERE shop_name=%s"
cursor.execute(query, (name,))
🗑️ Shop deleted successfully!")
con.commit()
print("

elif ch == 4:
cursor.execute("SELECT * FROM shops")

📋 Shop Records:")
records = cursor.fetchall()
print("\n
for row in records:
print(f"ID: {row[0]}, Name: {row[1]}, Floor:
{row[2]}, Area: {row[3]} sq.ft")

👋 Exiting the program.")


elif ch == 5:
print("
break

❌ Invalid choice. Please try again.")


else:
print("

❓ VIVA QUESTIONS & ANSWERS:


1. Write any three real-time applications used with MySQL database
connectivity?

●​ Property Management System​

●​ Hospital Patient Records​

●​ E-commerce Product Inventory​

2. What data types are commonly used in a property management database?

●​ INT (for shop_id, floor)​

●​ VARCHAR (for shop_name)​

●​ FLOAT or DECIMAL (for area in square feet)​


3. How does normalization help in property management databases?

Normalization avoids redundancy by organizing data into separate


related tables. This reduces storage and improves update efficiency and
data integrity.

4. What is the role of a primary key in a property management database?

It uniquely identifies each shop or property, ensuring data accuracy and


helping in record retrieval, update, or deletion.

5. How can you ensure security in a property management database?

●​ Use user authentication (MySQL users with restricted privileges)​

●​ Validate inputs (avoid SQL injection)​

●​ Implement encrypted connections​

●​ Use role-based access controls

EXP:17
SQL CODE:
CREATE DATABASE IF NOT EXISTS student_db;
USE student_db;
CREATE TABLE IF NOT EXISTS students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
roll_no VARCHAR(20),
department VARCHAR(100),
email VARCHAR(100)
);
SHOW CREATE TABLE students;

PYTHON
import mysql.connector
from flask import Flask, request, render_template

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])


def index():
if request.method == 'POST':
# Get form data
name = request.form['name']
age = request.form['age']
email = request.form['email']

try:
# Connect to MySQL
conn = mysql.connector.connect(
host='localhost',
user='root',
password='', # <-- Replace here
database='student_db' # <-- Replace here
)
cursor = conn.cursor()

# Insert query with placeholders


query = "INSERT INTO students (name, age, email)
VALUES (%s, %s, %s)"
values = (name, int(age), email) # Convert age to
int for safety

cursor.execute(query, values)
conn.commit()

cursor.close()
conn.close()

return "Student registered successfully!"

except mysql.connector.Error as err:


return f"Error: {err}"

return render_template('form.html') # Make sure form.html


is in templates folder

if __name__ == '__main__':
app.run(debug=True)
HTML //SUCCESS

<!DOCTYPE html>
<html>
<head>
<title>Success</title>
</head>
<body>
<h2>Registration Successful!</h2>
<p>Thank you, {{ name }}! You have successfully registered
for the {{ department }} course.</p>
</body>
</html>

VIVA:

Student Enrollment, E-Commerce Sites, and Hospital Management use


DB-connected frontends.​

Connect frontend to backend (e.g., Flask), then use Python to link with MySQL using
mysql.connector.​

Relational DBs ensure structured, secure, and scalable data with powerful SQL
queries.​

SQL Injection is a hacking technique to manipulate queries; it risks data theft or


deletion.​

Primary keys uniquely identify records and maintain data accuracy in student
databases.

EXP:18

VIVA QUESTIONS & 1-Line Answers

1.​ Write any 3 real-time applications of a hotel management system.​


➤ Online booking, inventory management, and automated billing.​
2.​ Which database is best for hotel management and why?​
➤ MySQL—it's reliable, scalable, and easy to integrate with Python.​

3.​ How do you handle customer check-in and check-out in the system?​
➤ By storing and updating check_in and check_out dates in the
database.​

4.​ What security measures should be in place for hotel data?​


➤ Strong passwords, encryption, and restricted access to the database.​

5.​ How can a hotel management system improve efficiency?​


➤ By automating reservations, billing, and tracking room availability in real
time.

EXP:18

CREATE DATABASE hotel_db;


USE hotel_db;
CREATE TABLE bookings (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100),
phone VARCHAR(20),
check_in DATE,
check_out DATE,
room_type VARCHAR(50)
);

PYTHON
from flask import Flask, request, render_template_string
import mysql.connector

app = Flask(__name__)

# MySQL connection config


db_config = {
'host': 'localhost',
'user': 'root',
'password': 'MYSQLdb-desh19', # <-- Replace with your
MySQL root password
'database': 'hotel_db'
}

form_html = """
<!doctype html>
<title>Hotel Booking Form</title>
<h2>Hotel Booking</h2>
<form method="POST" action="/">
Name: <input type="text" name="name" required><br><br>
Email: <input type="email" name="email" required><br><br>
Phone: <input type="text" name="phone" required><br><br>
Check-in Date: <input type="date" name="check_in"
required><br><br>
Check-out Date: <input type="date" name="check_out"
required><br><br>
Room Type:
<select name="room_type" required>
<option value="Single">Single</option>
<option value="Double">Double</option>
<option value="Suite">Suite</option>
</select><br><br>
<input type="submit" value="Book Now">
</form>
"""

@app.route('/', methods=['GET', 'POST'])


def booking():
if request.method == 'POST':
data = {
'name': request.form['name'],
'email': request.form['email'],
'phone': request.form['phone'],
'check_in': request.form['check_in'],
'check_out': request.form['check_out'],
'room_type': request.form['room_type']
}

try:
conn = mysql.connector.connect(**db_config)
cursor = conn.cursor()
sql = """INSERT INTO bookings (name, email, phone,
check_in, check_out, room_type)
VALUES (%s, %s, %s, %s, %s, %s)"""
cursor.execute(sql, tuple(data.values()))
conn.commit()
cursor.close()
conn.close()
return "<h3>Booking Successful! Thank you,
{}</h3>".format(data['name'])
except Exception as e:
return f"<h3>Error: {e}</h3>"

return render_template_string(form_html)

if __name__ == '__main__':
app.run(debug=True)

HTML //FORM

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width,
initial-scale=1" />
<title>Hotel Booking Form</title>
<style>
body {
font-family: Arial, sans-serif;
background: #f4f7f8;
padding: 20px;
}
.booking-form {
background: white;
max-width: 500px;
margin: 0 auto;
padding: 30px;
border-radius: 8px;
box-shadow: 0 0 15px rgba(0,0,0,0.1);
}
.booking-form h2 {
margin-bottom: 20px;
color: #333;
}
.booking-form label {
display: block;
margin-bottom: 6px;
font-weight: bold;
color: #555;
}
.booking-form input[type="text"],
.booking-form input[type="email"],
.booking-form input[type="date"],
.booking-form select,
.booking-form input[type="number"] {
width: 100%;
padding: 10px;
margin-bottom: 16px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
font-size: 16px;
}
.booking-form button {
background: #007bff;
color: white;
padding: 12px;
width: 100%;
border: none;
border-radius: 4px;
font-size: 18px;
cursor: pointer;
transition: background 0.3s ease;
}
.booking-form button:hover {
background: #0056b3;
}
</style>
</head>
<body>
<div class="booking-form">
<h2>Hotel Booking Form</h2>
<form action="/submit_booking" method="POST">
<label for="fullname">Full Name</label>
<input type="text" id="fullname" name="fullname"
required placeholder="Your full name" />

<label for="email">Email Address</label>


<input type="email" id="email" name="email"
required placeholder="[email protected]" />

<label for="phone">Phone Number</label>


<input type="text" id="phone" name="phone"
required placeholder="e.g. +91 9876543210" />

<label for="checkin">Check-In Date</label>


<input type="date" id="checkin" name="checkin"
required />

<label for="checkout">Check-Out Date</label>


<input type="date" id="checkout" name="checkout"
required />

<label for="roomtype">Room Type</label>


<select id="roomtype" name="roomtype" required>
<option value="" disabled selected>Select room
type</option>
<option value="single">Single Room</option>
<option value="double">Double Room</option>
<option value="suite">Suite</option>
</select>
<label for="guests">Number of Guests</label>
<input type="number" id="guests" name="guests"
min="1" max="10" value="1" required />

<button type="submit">Book Now</button>


</form>
</div>
</body>
</html>

HTML // BOOKING DONE

<!DOCTYPE html>
<html>
<head>
<title>Booking Confirmed</title>
</head>
<body>
<h2>Thank you {{ name }}!</h2>
<p>Your booking for a {{ room_type }} room from {{ check_in
}} to {{ check_out }} has been confirmed.</p>
</body>
</html>

You might also like