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

Unit 5 Lab Programs

This document outlines various exercises related to database and network programming using Python. It includes steps for connecting to a NoSQL database (MongoDB) using pymongo, iterating over records with cursors, implementing error handling for database operations, creating a TCP/IP client-server application, and sending emails using the SMTPLIB module. Each exercise provides algorithms, sample programs, and expected outputs.

Uploaded by

sibi00424
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 views18 pages

Unit 5 Lab Programs

This document outlines various exercises related to database and network programming using Python. It includes steps for connecting to a NoSQL database (MongoDB) using pymongo, iterating over records with cursors, implementing error handling for database operations, creating a TCP/IP client-server application, and sending emails using the SMTPLIB module. Each exercise provides algorithms, sample programs, and expected outputs.

Uploaded by

sibi00424
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/ 18

Unit 5 Database and Network

Ex.No 5.1: Connect to the NoSQL database using a Python connector module, such as
"pymongo" for MongoDB or "cassandra-driver" for Cassandra.

Aim: To Connect to MongoDb using a Python connector module.

Steps to be followed:

1. https://www.mongodb.com/try/download/community

Click The Select Package


2.

Click download, then the mongodb has been downloaded.

3.Open the exe file from download ,then click next.

4.In next window select the complete,then click next.

5.Mongodb will be downloaded in the PC.

6.Open command prompt

7.
8.

9.Open MongoCompass

10.Click Connect

11.Open IDLE type the program and run it.

Algorithm:

Step 1: Import Required Module

o Import the pymongo module to interact with MongoDB.


Step 2: Connect to MongoDB

o Use MongoClient('mongodb://localhost:27017') to establish a


connection to the local MongoDB server.

Step 3: Print the Connection Object

o Display the client object to verify the connection.

Step 4: Retrieve and List All Databases

o Use list_database_names() to fetch the names of all databases in the


MongoDB server.

Step 5: Print the List of Databases

o Display the list of databases retrieved.

Program:

import pymongo

client=pymongo.MongoClient('mongodb://localhost:27017')

print(client)

alldb=client.list_database_names()

print(alldb)

Output:
Ex.No:5.2: Use a cursor to iterate over the records in a collection/table and
print specific fields/attributes

Aim: Use a cursor to iterate over the records in a collection/table and print
specific fields/attributes

Algorithm:
Step 1.Import pymongo
Step 2.Connect with Mongocompas using MongoClient command
Step 3.Create a ‘Employee’ data base
Step 4.Create a collection ‘Information’
Step 5.Create a document rec with attributes
{EMPNO,ENAME,JOB,HIREDATE,SAL,DEPTNO}
Step 6.Finally insert the document into the collection using Insert_one or
insert_many command.
Step 7.Open the Mongodb .The created collection will be displayed.

Program:
import pymongo

client=pymongo.MongoClient('mongodb://localhost:27017')

mydb=client['Employee']

information=mydb.table

rec={

"EMPNO" : 7934,

"ENAME" : "AAAAA",

"JOB" : "CLERK",

"HIREDATE" : "1.08.2018",

"SAL" : 35000,

"DEPTNO" : 10

doc=information.insert_one(rec)

print(doc)

#Create a More one collection

import pymongo

client=pymongo.MongoClient('mongodb://localhost:27017')

mydb=client['Employee']

information=mydb.table

rec=[{

"EMPNO" : 7934,

"ENAME" : "AAAAA",

"JOB" : "CLERK",

"HIREDATE" : "1.08.2018",
"SAL" : 35000,

"DEPTNO" : 10

},

"EMPNO" : 7935,

"ENAME" : "BBBB",

"JOB" : "CODER",

"HIREDATE" : "1.08.2019",

"SAL" : 55000,

"DEPTNO" : 5

},

"EMPNO" : 7936,

"ENAME" : "CCCC",

"JOB" : "MANAGER",

"HIREDATE" : "1.08.2008",

"SAL" : 100000,

"DEPTNO" : 1 }

doc=information.insert_many(rec)

print(doc)

Output:
//find the collection

import pymongo

client=pymongo.MongoClient('mongodb://localhost:27017')

mydb=client['Employee']

information=mydb.table

read = information.find_one({"ENAME": "CCCC"})

print(read)

Output:

#Find all the collection

import pymongo

client=pymongo.MongoClient('mongodb://localhost:27017')

mydb=client['Employee']

information=mydb.table

#print the collection in the database

dis=information.find()

for record in dis:

print(record)
O/P:

Exp:5.3: Implement error handling for specific scenarios, such as duplicate key
violation or record not found, in the NoSQL database.

Aim: Implement error handling for specific scenarios, such as duplicate key
violation or record not found, in the MongoDB.

Algorithm:

Step 1: Import Required Modules

o Import MongoClient and errors from pymongo for database connection and
error handling.

Step 2: Connect to MongoDB

o Establish a connection to MongoDB at localhost:27017.


o Access the Company database.
o Access the Employees collection.

Step 3: Ensure Unique Index on employee_id


o Create a unique index on the employee_id field to prevent duplicate entries.

Step 4: Insert a Document with Duplicate Key Handling

o Define an employee document with employee_id, name, and department.


o Try inserting the document into the collection.
o If a duplicate key error occurs, print an error message.

Step 5: Find a Document with Record Not Found Handling

o Set an employee_id that does not exist in the database.


o Try retrieving the document using find_one().
o If the document is found, display it.
o If not found, raise and handle a ValueError.

Step 6: Handle General MongoDB Errors

o Try an invalid database operation (e.g., inserting an invalid field).


o Catch and handle OperationFailure and PyMongoError exceptions.

Step 7: Close the MongoDB Connection

o Use client.close() to safely close the database connection.

Program:
from pymongo import MongoClient, errors

# Connect to MongoDB
client = MongoClient("mongodb://localhost:27017")
db = client["Company"]
collection = db["Employees"]

# Ensure a unique index on "employee_id" to demonstrate duplicate


key error
collection.create_index("employee_id", unique=True)

# Insert a document (Handling Duplicate Key Error)


try:
employee = {"employee_id": 101, "name": "Alice",
"department": "HR"}
collection.insert_one(employee)
print("Document inserted successfully.")

employee = {"employee_id": 101, "name": "Krish",


"department": "EDP"}
collection.insert_one(employee)
print("Document inserted successfully.")

except errors.DuplicateKeyError:
print("Error: Duplicate key violation. Employee ID must be
unique.")

# Find a document (Handling Record Not Found)


try:
emp_id = 999 # Non-existent ID
result = collection.find_one({"employee_id": emp_id})

if result:
print("Employee Found:", result)
else:
raise ValueError("Record not found.")

except ValueError as e:
print(f"Error: {e}")

# General MongoDB Error Handling


try:
# Example: Trying an invalid operation
collection.insert_one({"$invalidField": "test"}) # Invalid
field name

except errors.OperationFailure as e:
print(f"MongoDB Operation Error: {e}")

except errors.PyMongoError as e:
print(f"General MongoDB Error: {e}")

finally:
client.close() # Close the connection

Output:
Error: Duplicate key violation. Employee ID must be unique.
Error: Record not found.

Ex.No:5.4
Implement a TCP/IP client-server application using the socket module for sending and
receiving messages.

Aim: Implement aTCP/IP client-server application using the socket module for sending
and receiving messages.

Algorithm for a Simple TCP Server Program


Step 1: Import Required Module

o Import the socket module to handle network communication.

Step 2: Define Server Settings

o Set HOST as '127.0.0.1' (localhost) or '0.0.0.0' (for accepting


connections from any IP).
o Set PORT as 12345 (ensure the client uses the same port).

Step 3: Create a Server Socket

o Use socket.socket(socket.AF_INET, socket.SOCK_STREAM)


to create an IPv4, TCP socket.
o Bind the socket to HOST and PORT using bind().
o Start listening for incoming connections with listen(5), allowing up to 5
clients to queue.

Step 4: Start Server Loop

o Display a message indicating the server is listening.

Step 5: Accept Client Connection

o Use accept() to wait for and accept a client connection.


o Retrieve the client socket and address.
o Print the client’s address.

Step 6: Receive Data from Client

o Use recv(1024).decode('utf-8') to receive up to 1024 bytes of data


and decode it.
o Print the received message.

Step 7: Send Response to Client

o Format a response message acknowledging receipt of the client’s data.


o Send the response back using send().

Step 8: Close the Client Connection

o Use close() to close the connection with the client.

Step 9: Repeat for New Clients

o The server continues running, accepting new connections in an infinite loop.


Program:
(i) Server Program:
import socket

# Server settings
HOST = '127.0.0.1' # Localhost (use '0.0.0.0' to accept connections from any IP)
PORT = 12345 # Port number (must match client)

# Create a socket (IPv4, TCP)


server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT)) # Bind to the IP and port
server_socket.listen(5) # Listen for up to 5 clients

print(f"Server listening on {HOST}:{PORT}...")

while True:
client_socket, client_address = server_socket.accept() # Accept a connection
print(f"Connection from {client_address}")

# Receive data from client


data = client_socket.recv(1024).decode('utf-8')
print(f"Received from client: {data}")

# Send response
response = f"Server received: {data}"
client_socket.send(response.encode('utf-8'))

# Close the connection


client_socket.close()

Algorithm for a Simple TCP Client Program

Step 1: Import Required Module

o Import the socket module to enable network communication.

Step 2: Define Server Details

o Set HOST as '127.0.0.1' (localhost) to connect to the local server.


o Set PORT as 12345, ensuring it matches the server's port.

Step 3: Create a Client Socket


o Use socket.socket(socket.AF_INET, socket.SOCK_STREAM)
to create an IPv4, TCP socket.

Step 4: Connect to the Server

o Use connect((HOST, PORT)) to establish a connection with the server.

Step 5: Send a Message to the Server

o Define a message ("Hello, Server!").


o Convert the message to bytes using encode('utf-8').
o Send the message using send().

Step 6: Receive Server Response

o Use recv(1024).decode('utf-8') to receive up to 1024 bytes of data


and decode it.
o Print the response from the server.

Step 7: Close the Connection

o Use close() to disconnect from the server.

Client Program
import socket

# Server details (should match server settings)


HOST = '127.0.0.1'
PORT = 12345

# Create a socket (IPv4, TCP)


client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((HOST, PORT)) # Connect to server

# Send message
message = "Hello, Server!"
client_socket.send(message.encode('utf-8'))

# Receive response
response = client_socket.recv(1024).decode('utf-8')
print(f"Received from server: {response}")

# Close the connection


client_socket.close()
How to run the Programs?

1. Open Command prompt and run server.py

Output:

2. Open another instance of the command prompt and run client.py

Output:

Ex. No: 5.5:


Write a program using the SMTPLIB module to send an email from a specified email address to
another recipient.

Aim: To write a python program using the SMTPLIB module to send an email from a specified
email address to another recipient.

Algorithm:

Step 1: Import Required Modules

o Import smtplib for handling email sending.


o Import MIMEText and MIMEMultipart from email.mime.text and
email.mime.multipart to construct the email.

Step 2: Define Email Configuration

o Set the SMTP server (smtp.gmail.com for Gmail).


o Set the SMTP port (587 for TLS).
o Define sender email credentials (email and app password).
o Define the recipient email address.

Step 3: Compose the Email

o Define the subject and body of the email.


o Create a MIMEMultipart message object.
o Set sender, recipient, and subject fields in the message.
o Attach the email body as plain text.

Step 4: Establish Connection with SMTP Server

o Create an SMTP object with the server and port.


o Initiate a secure connection using starttls().
o Log in using the sender’s email and app password.

Step 5: Send the Email

o Use sendmail() to send the email from sender to recipient.


o Display a success message if sent successfully.

Step 6: Handle Errors

o Use a try-except block to catch and display any errors.

Step 7: Close the SMTP Connection

o Ensure the SMTP server connection is closed using server.quit() inside a


finally block.

Program:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# Email Configuration
SMTP_SERVER = "smtp.gmail.com" # Change for Yahoo, Outlook, etc.
SMTP_PORT = 587 # Port for TLS

SENDER_EMAIL = "sender@gmail.com" # Replace with your email


SENDER_PASSWORD = "app password" # Use App Password, not regular password
RECIPIENT_EMAIL = "receiver@gmail.com" # Recipient's email

# Email Content
subject = "Test Email from Python"
body = "Hello,\n\nThis is a test email sent using Python and smtplib.\n\nBest Regards,\nYour
Name"

# Create Email Message


msg = MIMEMultipart()
msg["From"] = SENDER_EMAIL
msg["To"] = RECIPIENT_EMAIL
msg["Subject"] = subject
msg.attach(MIMEText(body, "plain"))

try:
# Connect to SMTP Server
server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
server.starttls() # Secure connection using TLS
server.login(SENDER_EMAIL, SENDER_PASSWORD) # Login to email account

# Send Email
server.sendmail(SENDER_EMAIL, RECIPIENT_EMAIL, msg.as_string())

print("✅Email sent successfully!")

except Exception as e:
print(f"✅Error: {e}")

finally:
server.quit() # Close the connection

How to run the Program?


1. Create app password for senders gmail account. For details see
https://www.youtube.com/watch?v=MkLX85XU5rU

2. Give valid sender and receiver mail ids and run the python program

Output:

You might also like