UNIT-5 14M
UNIT-5 14M
14 MARKS:
1.Ellaborate SQL Libraries in other databases with example.
SQL Libraries in Other Databases with Examples
SQL libraries in Python allow you to connect, interact with, and manage different types of databases.
These libraries provide an interface for executing SQL queries, fetching results, handling database
connections, and performing other database-related operations. Although the most common SQL
library in Python is sqlite3 (for SQLite databases), Python supports a variety of SQL databases,
including MySQL, PostgreSQL, Oracle, SQL Server, and others, each with its own corresponding
library.
Here’s an overview of some of the widely used libraries for connecting to SQL databases, along with
examples of how to use them:
1. SQLite: sqlite3
import sqlite3
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
# Create a table
cursor.execute('''CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age
INTEGER)''')
# Query data
rows = cursor.fetchall()
print(row)
conn.close()
Common Operations:
2. MySQL: mysql-connector-python
MySQL is a widely used open-source relational database management system. The mysql-connector-
python library is used to interact with MySQL databases in Python.
Installation:
import mysql.connector
conn = mysql.connector.connect(
cursor = conn.cursor()
# Create a table
cursor.execute("CREATE TABLE IF NOT EXISTS users (id INT AUTO_INCREMENT PRIMARY KEY, name
VARCHAR(100), age INT)")
cursor.execute("INSERT INTO users (name, age) VALUES (%s, %s)", ("Alice", 30))
cursor.execute("INSERT INTO users (name, age) VALUES (%s, %s)", ("Bob", 25))
conn.commit()
# Query data
print(row)
conn.close()
Common Operations:
PostgreSQL is an advanced open-source relational database system. The psycopg2 library is the most
popular PostgreSQL database adapter for Python.
Installation:
import psycopg2
conn = psycopg2.connect(
cursor = conn.cursor()
# Create a table
cursor.execute("CREATE TABLE IF NOT EXISTS users (id SERIAL PRIMARY KEY, name VARCHAR(100),
age INT)")
cursor.execute("INSERT INTO users (name, age) VALUES (%s, %s)", ("Alice", 30))
cursor.execute("INSERT INTO users (name, age) VALUES (%s, %s)", ("Bob", 25))
conn.commit()
# Query data
print(row)
conn.close()
Common Operations:
4. Oracle: cx_Oracle
Oracle Database is a multi-model database management system. The cx_Oracle library is used to
connect to Oracle databases from Python.
Installation:
import cx_Oracle
conn = cx_Oracle.connect(
cursor = conn.cursor()
# Create a table
cursor.execute('''
name VARCHAR2(100),
age NUMBER
''')
cursor.execute("INSERT INTO users (id, name, age) VALUES (1, 'Alice', 30)")
cursor.execute("INSERT INTO users (id, name, age) VALUES (2, 'Bob', 25)")
conn.commit()
# Query data
print(row)
conn.close()
Common Operations:
Installation:
import pyodbc
conn = pyodbc.connect(
'SERVER=localhost;'
'DATABASE=test_db;'
'UID=sa;'
'PWD=password'
cursor = conn.cursor()
# Create a table
cursor.execute('''
name VARCHAR(100),
age INT
''')
cursor.execute("INSERT INTO users (id, name, age) VALUES (1, 'Alice', 30)")
cursor.execute("INSERT INTO users (id, name, age) VALUES (2, 'Bob', 25)")
# Commit the transaction
conn.commit()
# Query data
print(row)
conn.close()
Common Operations:
Graphical User Interface (GUI) programming allows developers to create interactive programs with
graphical elements such as buttons, text boxes, and images. In Python, there are several libraries for
creating GUIs, with Tkinter, PyQt, and Kivy being some of the most popular.
In this discussion, we'll focus on Tkinter, which is the standard library for GUI programming in
Python. It is widely used due to its simplicity and the fact that it comes pre-installed with Python,
making it very accessible for beginners.
1. Tkinter Overview
Tkinter is the Python interface to the Tk GUI toolkit. Tk was developed as a GUI library for the Tcl
programming language and later became the standard for many different programming languages,
including Python. Tkinter allows you to create windows, dialogs, and widgets such as buttons, labels,
entry fields, and menus, all with ease.
• Widgets: Elements like buttons, labels, text boxes, and entry fields.
• Geometry Management: Controls how widgets are arranged in the window (e.g., pack, grid,
or place).
• Event Handling: Binds events such as mouse clicks, key presses, etc., to functions.
2. Tkinter Basics
To use Tkinter, you need to import it into your Python program. Below is an example that creates a
simple window with a button.
import tkinter as tk
def on_button_click():
label.config(text="Hello, Tkinter!")
root = tk.Tk()
label.pack(pady=20)
button.pack(pady=10)
root.mainloop()
Explanation:
5. tk.Button(): Creates a button widget, and the command argument is used to link the button
to a function (on_button_click).
6. pack(): Places the widget in the window using the pack geometry manager.
7. root.mainloop(): Starts the Tkinter event loop, which keeps the window running.
When you run the program, you will see a window with a label and a button. When you click the
button, the text in the label changes.
In Tkinter, there are three main ways to manage the layout of widgets in a window:
import tkinter as tk
def on_button_click():
root = tk.Tk()
# Create widgets
# Grid layout
root.mainloop()
Explanation:
• grid(row, column): Positions the widgets in a grid layout, with the specified row and column.
• padx and pady: Add padding around the widget for better spacing.
In this example, the label and button are arranged in a simple grid layout.
Event handling in Tkinter is done using event bindings. You can bind functions to different events like
mouse clicks, key presses, and window resizing.
import tkinter as tk
def on_key_press(event):
root = tk.Tk()
# Create a label
label.pack(pady=20)
# Bind events
root.mainloop()
Explanation:
• bind("<Key>", on_key_press): Binds the on_key_press function to any key press event.
• bind("<Button-1>", on_click): Binds the on_click function to a left mouse button click event.
• The event object passed to the function contains useful information like the key that was
pressed or the coordinates of the mouse click.
Tkinter also provides several other widgets that can be used to create more advanced applications,
including:
import tkinter as tk
# Function to display text from entry field
def show_entry():
entered_text = entry.get()
root = tk.Tk()
# Create widgets
# Menu creation
menu = tk.Menu(root)
root.config(menu=menu)
file_menu = tk.Menu(menu)
menu.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="Exit", command=root.quit)
root.mainloop()
Explanation:
• Menu: A dropdown menu with options. In this case, we have added an "Exit" option under
the "File" menu.
As a practical example, we can create a simple calculator with a GUI that performs basic arithmetic
operations.
import tkinter as tk
def on_button_click(value):
current = entry.get()
entry.delete(0, tk.END)
def on_clear():
entry.delete(0, tk.END)
def on_equals():
try:
result = eval(entry.get())
entry.delete(0, tk.END)
entry.insert(0, result)
except Exception as e:
entry.delete(0, tk.END)
entry.insert(0, "Error")
root = tk.Tk()
root.title("Simple Calculator")
# Create entry field
# Create buttons
buttons = [
if text == '=':
else:
root.mainloop()
Explanation:
• This program creates a simple calculator that can perform basic arithmetic using eval() to
evaluate expressions.
• The buttons are dynamically created in a loop and placed in a grid layout.
• The on_button_click function adds digits and operators to the entry field.
• The on_equals function evaluates the expression in the entry field and displays the result.
3.Discuss in detail about SQL statements for data manipulation with example.
SQL Statements for Data Manipulation
SQL (Structured Query Language) provides several types of statements for manipulating data stored
in a relational database. The primary types of SQL statements for data manipulation are:
These SQL operations allow you to interact with and manage the data stored in the database. Let's
dive into each of these in detail, along with examples.
1. SELECT Statement
The SELECT statement is used to query the database and retrieve data from one or more tables. It is
the most commonly used SQL statement.
Syntax:
FROM table_name
WHERE condition;
Example:
FROM employees
This query retrieves the name and age columns from the employees table where the age is greater
than 30.
Explanation:
• WHERE age > 30: Filters the rows where the age column is greater than 30.
Variations:
2. INSERT Statement
Syntax:
• column1, column2, ...: The columns into which the data will be inserted.
• value1, value2, ...: The values to insert into the respective columns.
Example:
This query inserts a new record into the employees table, specifying values for the name, age, and
department columns.
Explanation:
• INSERT INTO employees (name, age, department): Specifies the table and columns.
Variations:
3. VALUES
4. ('Alice Smith', 35, 'Engineering'),
3. UPDATE Statement
Syntax:
UPDATE table_name
WHERE condition;
• SET column1 = value1, column2 = value2, ...: Specifies the columns and their new values.
• WHERE: Filters the rows that will be updated (optional but highly recommended to avoid
updating all rows).
Example:
UPDATE employees
SET age = 29
This query updates the age of the employee named John Doe to 29.
Explanation:
• WHERE name = 'John Doe': Applies the update only to rows where the name is 'John Doe'.
Variations:
2. UPDATE employees
This query updates both the age and department for the employee 'Alice Smith'.
6. UPDATE employees
7. SET department = 'Sales';
This updates the department for all employees to 'Sales' (be cautious with such queries).
4. DELETE Statement
The DELETE statement is used to remove records from a table. You can specify a condition to delete
only certain rows.
Syntax:
WHERE condition;
• WHERE: A condition to specify which rows to delete (optional but strongly recommended).
Example:
This query deletes the record of the employee named 'Bob Johnson' from the employees table.
Explanation:
• DELETE FROM employees: Specifies the table from which to delete data.
• WHERE name = 'Bob Johnson': Deletes only the row where the name is 'Bob Johnson'.
Variations:
This deletes all records in the employees table (without removing the table itself). Use with caution!
You can combine multiple SQL statements in a transaction to ensure data consistency and perform
complex operations.
BEGIN;
INSERT INTO employees (name, age, department)
UPDATE employees
COMMIT;
• If an error occurs, you can use ROLLBACK; to undo all changes made in the transaction.
SQL also provides several built-in functions to manipulate and aggregate data, such as:
Example:
This query returns the total number of employees in the 'HR' department.
4.Discuss in detail about Creating simple GUI using Tkinter with example.
Creating a Simple GUI Using Tkinter in Python
Tkinter is the standard Python library for creating graphical user interfaces (GUIs). It provides a
simple way to build windows, add buttons, labels, text boxes, and other common GUI elements,
making it ideal for beginners and small desktop applications.
In this guide, we will walk through the process of creating a simple GUI using Tkinter, including how
to set up the window, add widgets (like buttons and labels), and handle events like button clicks.
1. Overview of Tkinter
Tkinter is built on the Tk GUI toolkit, which is cross-platform and provides the following key
components for building a GUI application:
• Event Handling: The mechanism that listens for events (such as button clicks or keyboard
inputs) and triggers functions.
• Geometry Managers: These help to arrange and manage the position of widgets within a
window. The common geometry managers in Tkinter are pack(), grid(), and place().
2. Create the main window: The main window is where all widgets are placed.
3. Create widgets: Add interactive elements like buttons, labels, and entry fields.
4. Pack or grid widgets: Organize the layout of the widgets in the window.
6. Run the Tkinter event loop: Keeps the window open and interactive.
Let's create a simple GUI that displays a button. When the user clicks the button, a label's text will
change.
Code Example:
import tkinter as tk
# Function that will be called when the button is clicked
def change_text():
label.config(text="Hello, Tkinter!")
root = tk.Tk()
root.geometry("300x200")
label.pack(pady=20)
button.pack(pady=10)
root.mainloop()
3. root.geometry("300x200"): Sets the window's dimensions (300 pixels wide by 200 pixels
tall).
4. label = tk.Label(root, text="Click the button", font=("Arial", 14)): Creates a label widget
with some text.
5. label.pack(pady=20): Adds the label widget to the window, with vertical padding of 20 pixels.
6. button = tk.Button(root, text="Click Me", command=change_text): Creates a button widget
with the text "Click Me". The command parameter specifies the function to call when the
button is clicked.
7. root.mainloop(): Starts the Tkinter event loop, which keeps the window open and listens for
events (such as button clicks).
When you run the program, a window with a button will appear. When you click the button, the
label's text will change to "Hello, Tkinter!".
Now, let's create a more interactive program that allows the user to type their name into a text entry
field and display a greeting message when they click a button.
Code Example:
import tkinter as tk
def greet_user():
label.config(text=f"Hello, {name}!")
root = tk.Tk()
root.title("Name Greeting")
root.geometry("300x200")
label.pack(pady=10)
# Create an entry widget for user input
entry.pack(pady=10)
button.pack(pady=10)
root.mainloop()
1. entry = tk.Entry(root, font=("Arial", 14)): Creates an entry field where users can type their
name.
3. label.config(text=f"Hello, {name}!"): Updates the label to greet the user by their name
when the button is clicked.
• The window shows a label prompting the user to enter their name.
• When the user types their name and clicks the "Greet Me" button, the program displays a
personalized greeting.
In Tkinter, you can arrange widgets within the window using different geometry managers: pack(),
grid(), and place(). We'll explore pack() and grid() here.
import tkinter as tk
root = tk.Tk()
root.geometry("300x200")
label.pack(padx=20, pady=20)
button.pack()
root.mainloop()
In this example, we use pack() to place the label and button within the window. The padx and pady
parameters add horizontal and vertical padding, respectively.
import tkinter as tk
root = tk.Tk()
root.geometry("300x200")
root.mainloop()
Explanation of grid():
• grid(row, column): Places widgets in a grid at the specified row and column.
In Tkinter, you can handle various events like button clicks, mouse movements, or keyboard presses
using event bindings.
import tkinter as tk
def on_button_click(event):
root = tk.Tk()
label.pack(pady=20)
button.pack(pady=10)
button.bind("<Button-1>", on_button_click)
root.mainloop()
Explanation:
• button.bind("<Button-1>", on_button_click): This binds the left mouse button click (Button-
1) to the on_button_click function. When the button is clicked, the label's text is updated.