0% found this document useful (0 votes)
4 views16 pages

Advance Python Chapter 4

This document covers various aspects of using Django and MySQL with Python, including creating databases and tables, inserting and fetching records, and updating data using Tkinter for GUI. It explains the concepts of models, database fields, and Object-Relational Mapping (ORM) in Python. Additionally, it provides code examples for database operations and highlights the advantages of integrating databases with Tkinter applications.

Uploaded by

disecek477
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)
4 views16 pages

Advance Python Chapter 4

This document covers various aspects of using Django and MySQL with Python, including creating databases and tables, inserting and fetching records, and updating data using Tkinter for GUI. It explains the concepts of models, database fields, and Object-Relational Mapping (ORM) in Python. Additionally, it provides code examples for database operations and highlights the advantages of integrating databases with Tkinter applications.

Uploaded by

disecek477
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/ 16

Advance Python Chapter 4

[Q-4]

(A)

1. Django automatically creates a _____ database for your project.


➢ SQLite3

2. By default ______ file is used as a Django setting file.


➢ settings.py

3. ______ module is used to connect python application with the MySQL.


➢ MySQL Connector (or mysqlclient)

4. Define model.
➢ A model in Django is a Python class that defines the structure of a
database table.

5. Which Query is use to display the data from the table?


➢ SELECT query is used to display data from the table.
➢ E.g: SELECT col_names FROM table_name

6. Which Query is use to delete the data from the table?


➢ DELETE query is used to display data from the table.
➢ E.g: DELETE FROM table_name WHERE id=1
(B)

1. Write down the code to create database.

import mysql.connector
import tkinter as tk

def create_database():
conn = mysql.connector.connect(
host="localhost",
user="root",
password=""
)
cursor = conn.cursor()
cursor.execute("CREATE DATABASE IF NOT EXISTS mydatabase
conn.close()

# Create Tkinter window


root = tk.Tk()
root.title("Create MySQL Database")

# Create a button to trigger database creation


btn_create = tk.Button(root, text="Create Database",
command=create_database)
btn_create.pack(pady=20)

root.mainloop()
2. Write down the code to create table.

import mysql.connector
import tkinter as tk

def create_table():
conn = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="mydatabase"
)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
age INT NOT NULL
)
""")
conn.close()

# Create Tkinter window


root = tk.Tk()
root.title("Create MySQL Table")

# Create a button to trigger table creation


btn_create = tk.Button(root, text="Create Table", command=create_table)
btn_create.pack(pady=20)

root.mainloop()
3. Write down the code to insert 5 records in the table (table name:
student).

import mysql.connector
import tkinter as tk

def insert_records():
conn = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="mydatabase"
)
cursor = conn.cursor()

# Query to insert records


query = "INSERT INTO student (name, age) VALUES (%s, %s)"

# Records to be inserted
records = [
("Alice", 20),
("Bob", 21),
("Charlie", 22),
("David", 23),
("Eve", 20)
]

# Execute query
cursor.executemany(query, records)

conn.commit()
conn.close()

# Create Tkinter window


root = tk.Tk()
root.title("Insert Records into Student Table")

# Create a button to insert records


btn_insert = tk.Button(root, text="Insert Records", command=insert_records)
btn_insert.pack(pady=20)

root.mainloop()
4. Write down the code to fetch all data from table.

import mysql.connector
import tkinter as tk

def fetch_data():
conn = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="mydatabase"
)
cursor = conn.cursor()

# Query to fetch all data


fetch_query = "SELECT * FROM student"
cursor.execute(fetch_query)
records = cursor.fetchall()

conn.close()

# Display records in the text widget


text_display.delete("1.0", tk.END) # Clear previous content
for record in records:
text_display.insert(tk.END, f"{record}\n")

# Create Tkinter window


root = tk.Tk()
root.title("Fetch Data from Student Table")

# Create a button to fetch data


btn_fetch = tk.Button(root, text="Fetch Data", command=fetch_data)
btn_fetch.pack(pady=10)

# Create a Text widget to display fetched data


text_display = tk.Text(root, width=50, height=10)
text_display.pack(pady=10)

root.mainloop()
5. Explain get( ) and filter( ) method for update operations.
➢ get() Method:
o The get() method retrieves a single object from the database.
o It is used when we know that only one record matches the
condition.
o After fetching the object, we update its fields and call save().
o If no record is found or multiple records exist, it raises an error.

student = Student.objects.get(id=1)
student.name = "Updated Name"
student.save()

➢ filter() Method:
o he filter() method retrieves a QuerySet (multiple records)
matching the condition.
o We use .update() to modify multiple records at once.
o It does not require calling save() separately.

Student.objects.filter(age=20).update(name="Updated Name")
6. Explain Model class and variable.
➢ In Django, a Model class is used to define the structure of a database
table.
➢ It is created in the models.py file and works with Django’s Object-
Relational Mapping (ORM) to interact with the database.
➢ Allows CRUD operations (Create, Read, Update, Delete) without writing
raw SQL queries.
➢ Provides data validation using built-in field types.
➢ Example:
from django.db import models

class Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
email = models.EmailField(unique=True)

➢ Model Variables:
o Model variables (fields) define the columns of the table.
o Each variable has a data type that specifies the type of data it can
store.
o name Stores student names (text).
o age Stores student ages (numbers).
o email Stores unique student emails.
7. Explain database fields.
➢ In Django, a database field is an attribute of a model that represents a
column in a database table.
➢ Each field is defined using Django's built-in field types in the models.py
file.
➢ Example:
from django.db import models

class Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
email = models.EmailField(unique=True)
admission_date = models.DateField()
➢ Text Fields:
o CharField(max_length=100): Stores short text (e.g., names).
o TextField(): Stores long text (e.g., descriptions).
➢ Number Fields:
o IntegerField(): Stores whole numbers.
o FloatField(): Stores decimal numbers.
➢ Boolean Field:
o BooleanField(): Stores True or False values.
➢ Date and Time Fields:
o DateField(): Stores a date.
o DateTimeField(): Stores date and time.
➢ Other Fields:
o EmailField(): Stores emails.
o URLField(): Stores website URLs.
(C)

1. Write down the code to display records from the student table on the
base of the name field.

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

# Database Connection
conn = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="mydatabase"
)
cursor = conn.cursor()

# Function to fetch student data by name


def fetch_data():
name = entry_name.get() # Get the entered name

# Fetch records matching the entered name


cursor.execute("SELECT * FROM student WHERE name = %s", (name,))
records = cursor.fetchall()

# Clear previous text


text_display.delete("1.0", tk.END)

# Display results
if records:
for record in records:
text_display.insert(tk.END, f"ID: {record[0]}, Name:
{record[1]}, Age: {record[2]}\n")

# Tkinter GUI
root = tk.Tk()
root.title("Fetch Student Records")

# Name Label and Entry


tk.Label(root, text="Enter Student Name:").pack()
entry_name = tk.Entry(root)
entry_name.pack()
# Fetch Button
tk.Button(root, text="Fetch Data", command=fetch_data).pack()
# Display Area
text_display = tk.Text(root, width=50, height=10)
text_display.pack()

root.mainloop()
2. Write down the code to update any three records on the base of the
name field and display all the records.

import mysql.connector
import tkinter as tk

# Connect to MySQL database


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

# Update three records based on name


updates = [("John", 30), ("Alice", 25), ("Bob", 28)]
for name, age in updates:
cur.execute("UPDATE users SET age=%s WHERE name=%s", (age, name))
conn.commit()

# Fetch all records


cur.execute("SELECT * FROM users")
rows = cur.fetchall()

# Tkinter GUI
root = tk.Tk()
root.title("User Records")

listbox = tk.Listbox(root, width=50)


listbox.pack(pady=10)

# Insert data into Listbox


for row in rows:
listbox.insert(tk.END, f"ID: {row[0]}, Name: {row[1]}, Age: {row[2]}")

root.mainloop()
conn.close()
3. Write down the code to access data from emp table those who earn
salary more than average salary. Table Name emp Columns empno,
ename, deptno, salary

import mysql.connector
import tkinter as tk

# Connect to MySQL database


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

# Fetch employees earning more than the average salary


cur.execute("SELECT empno, ename, deptno, salary FROM emp WHERE salary >
(SELECT AVG(salary) FROM emp)")
rows = cur.fetchall()

# Tkinter GUI
root = tk.Tk()
root.title("Employees with Salary > Avg Salary")

listbox = tk.Listbox(root, width=60)


listbox.pack(pady=10)

# Insert data into Listbox


listbox.insert(tk.END, "EmpNo | Name | DeptNo | Salary")
listbox.insert(tk.END, "-" * 40)

for row in rows:


listbox.insert(tk.END, f"{row[0]} | {row[1]} | {row[2]} | {row[3]}")

root.mainloop()
conn.close()
4. Explain database defining Model in Python.
➢ A database model in Python is a structured representation of a database
table using Object-Relational Mapping (ORM).
➢ Instead of writing raw SQL queries, Python classes define how data is
stored, retrieved, and manipulated.
➢ Using ORM provides:
o Better Code Readability – No need to write complex SQL queries.
o Security – Protects against SQL injection.
o Portability – Works with multiple database systems (e.g., SQLite,
MySQL, PostgreSQL).
➢ Popular ORMs in Python include:
o Django ORM – Used in Django framework.
o SQLAlchemy – General-purpose ORM for Python applications.
➢ Example:

from django.db import models

class Employee(models.Model):
ename = models.CharField(max_length=100)
deptno = models.IntegerField()
salary = models.DecimalField(max_digits=10, decimal_places=2)
def __str__(self):
return self.ename
➢ A model is a class that represents a table in the database. Each attribute
of the class corresponds to a column in the table.
➢ Once the model is defined, it needs to be migrated to create a database
table.
➢ In Django, run these commands:
o python manage.py makemigrations
o python manage.py migrate
➢ Importance of Database Models:
o Abstraction – Developers work with objects instead of SQL queries.
o Data Validation – Enforces data integrity (e.g., maximum length in
CharField).
o Scalability – Easily modify the model and update the database
structure.
o Cross-Database Support – Works with multiple database backends
without changing code.
5. Explain Database with Tkinter in details.
➢ Tkinter is the standard GUI library in Python, used for building graphical
applications. When combined with a database (such as MySQL or SQLite),
it allows users to store, retrieve, and manipulate data through an
interactive interface.
➢ Common Applications:
o Employee management systems
o Student record management
o Inventory management
➢ To use a database in Tkinter, first establish a connection.
➢ Tkinter widgets like Entry, Button, Label, and Listbox are used to display
and manage database data.

import tkinter as tk
import mysql.connector

# Connect to MySQL
conn = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="test_db"
)
cur = conn.cursor()

def insert_data():
name = entry_name.get()
salary = entry_salary.get()
cur.execute("INSERT INTO emp (name, salary) VALUES (%s, %s)",
(name, salary))
conn.commit()
show_data()

# Tkinter GUI
root = tk.Tk()
root.title("Employee Database")

tk.Label(root, text="Name:").pack()
entry_name = tk.Entry(root)
entry_name.pack()

tk.Label(root, text="Salary:").pack()
entry_salary = tk.Entry(root)
entry_salary.pack()

tk.Button(root, text="Add Employee", command=insert_data).pack()


root.mainloop()

conn.close()
➢ Advantages:
o Data Persistence – Stores data permanently.
o Easy Data Handling – GUI simplifies interaction.
o User-Friendly Interface – No need to use command-line SQL.
o Real-Time Updates – Fetch and display updated data dynamically.

You might also like