0% found this document useful (0 votes)
21 views7 pages

CSE 4508 RDBMS Lab Task Winter 2024

Uploaded by

fatema
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)
21 views7 pages

CSE 4508 RDBMS Lab Task Winter 2024

Uploaded by

fatema
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/ 7

Lab 5

Complex Data Types

CSE 4508
RELATIONAL DATABASE MANAGEMENT SYSTEM LAB

NOVEMBER 5, 2024
Winter 2024 Complex Data Types Lab 5

Contents

1 JSON 2
1.1 Understanding JavaScript Object Notation (JSON) . . . . . . . . . . . . . . . . . 2
1.2 Working with JSON in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Accessing Nested JSON Data in Python . . . . . . . . . . . . . . . . . . . . . . . . 2
1.4 Accessing Arrays in JSON . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

2 SQLAlchemy 3
2.1 Setting up a Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.2 Defining Models (Tables) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.3 Creating a Session . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.4 CRUD Operations with SQLAlchemy . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.4.1 Create: Adding a New User to the Database . . . . . . . . . . . . . . . . 4
2.4.2 Read: Querying Users from the Database . . . . . . . . . . . . . . . . . . 4
2.4.3 Update: Updating an Existing User’s Age . . . . . . . . . . . . . . . . . . 4
2.4.4 Delete: Deleting a User from the Database . . . . . . . . . . . . . . . . . 4
2.5 Working with Relationships . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

3 Lab Tasks 5

1
Winter 2024 Complex Data Types Lab 5

1 JSON
1.1 Understanding JavaScript Object Notation (JSON)
• Lightweight data-interchange format, commonly used for APIs.

• JSON syntax:

– Key-value pairs
– Arrays and nested objects

Example JSON Data:


{
" user " : {
" name " : " John Doe " ,
" age " : 3 0 ,
" address " : {
" city " : " New York " ,
" postalCode " : " 10001 "
},
" hobbies " : [ " reading " , " gaming " , " hiking " ]
}
}

1.2 Working with JSON in Python


Code Example: Parsing JSON
import json
data = ’ ’ ’{
" user ": {
" name ": " John Doe " ,
" age ": 30 ,
" address ": {
" city ": " New York " ,
" postalCode ": "10001"
},
" hobbies ": [" reading " , " gaming " , " hiking "]
}
}’’’
parsed_data = json . loads ( data )
print ( parsed_data ) # Outputs the full dictionary

1.3 Accessing Nested JSON Data in Python

name = parsed_data [" user "][" name "]


age = parsed_data [" user "][" age "]
city = parsed_data [" user "][" address "][" city "]
postal_code = parsed_data [" user "][" address "][" postalCode "]

# Displaying the extracted values


print (" Name :" , name ) # Output : John Doe
print (" Age :" , age ) # Output : 30
print (" City :" , city ) # Output : New York
print (" Postal Code :" , postal_code ) # Output : 10001

2
Winter 2024 Complex Data Types Lab 5

1.4 Accessing Arrays in JSON

# Accessing the ’ hobbies ’ array


hobbies = parsed_data [" user "][" hobbies "]
print (" Hobbies :" , hobbies ) # Output : [ ’ reading ’ , ’ gaming ’ , ’ hiking
’]

# Iterating through the array of hobbies


for hobby in hobbies :
print (" Hobby :" , hobby )

2 SQLAlchemy
SQLAlchemy is a powerful SQL toolkit and Object-Relational Mapping (ORM) library for
Python. It provides both Core (for SQL expressions) and ORM (for mapping tables to
classes). It is used to interact with relational databases (SQLite, PostgreSQL, MySQL).

2.1 Setting up a Connection

import os
from sqlalchemy import create_engine , Column , Integer , String ,
ForeignKey
from sqlalchemy . ext . declarative import declarative_base
from sqlalchemy . orm import sessionmaker , relationship
# Connecting to an SQLite database ( or creating it if it doesn ’ t
exist )
current_direc tory = os . path . dirname ( os . path . abspath ( __file__ ) )
database_path = os . path . join ( current_directory , ’ example . db ’)
engine = create_engine (f ’ sqlite :///{ database_path } ’)

2.2 Defining Models (Tables)

# Defining a Model for a ‘ User ‘ Table :


Base = declarative_base ()

class User ( Base ) :


__tablename__ = ’ users ’ # Specifies the table name
id = Column ( Integer , primary_key = True )
name = Column ( String )
age = Column ( Integer )

# Create all tables defined with Base


Base . metadata . create_all ( engine )

2.3 Creating a Session


A session manages database transactions. Use it to add, query, and modify objects in the
database.
# Bind session to the engine
Session = sessionmaker ( bind = engine )
session = Session ()

3
Winter 2024 Complex Data Types Lab 5

2.4 CRUD Operations with SQLAlchemy


2.4.1 Create: Adding a New User to the Database

new_user = User ( name =" Alice " , age =25)


session . add ( new_user )
session . commit ()

2.4.2 Read: Querying Users from the Database

# Fetch the first user with the name " Alice "
user = session . query ( User ) . filter_by ( name =" Alice ") . first ()
print ( user . name , user . age ) # Output : Alice 25

2.4.3 Update: Updating an Existing User’s Age

user = session . query ( User ) . filter_by ( name =" Alice ") . first ()
user . age = 26 # Update the age
session . commit () # Save the changes

2.4.4 Delete: Deleting a User from the Database

user = session . query ( User ) . filter_by ( name =" Alice ") . first ()
session . delete ( user ) # Mark the user for deletion
session . commit () # Commit the deletion

2.5 Working with Relationships

from sqlalchemy import ForeignKey


from sqlalchemy . orm import relationship

class Address ( Base ) :


__tablename__ = ’ addresses ’
id = Column ( Integer , primary_key = True )
email = Column ( String , nullable = False )
user_id = Column ( Integer , ForeignKey ( ’ users . id ’) ) # Foreign
key linking to User

user = relationship (" User " , back_populates =" addresses ") #


Define the relationship

User . addresses = relationship (" Address " , order_by = Address . id ,


back_populates =" user ")
With this setup, each ‘User‘ can have multiple ‘Address‘ entries associated with it, enabling
more complex data models.

4
Winter 2024 Complex Data Types Lab 5

3 Lab Tasks
1. Parse the JSON data and print the store’s "name" and its "city" location.
2. Access and print the names and prices of all products in the "Electronics" department.
3. Extract and print the "brand" and "specifications" of the product with the name "Wire-
less Mouse".
4. Modify the "price" of the "Smartphone" product to 749.99 and print the updated JSON.

Column Name Data Type Description Constraints


id Integer Unique identifier for each book Primary Key
title String Title of the book Not Null
author String Author of the book Not Null
published_year Integer Year the book was published Not Null
price Float Price of the book Not Null

Table 1: Database Structure for Book Table

id title author published_year price


1 The Great Gatsby F. Scott Fitzgerald 1925 10.99
2 To Kill a Mockingbird Harper Lee 1960 7.99
3 1984 George Orwell 1949 8.99
4 Pride and Prejudice Jane Austen 1813 5.99
5 The Catcher in the Rye J.D. Salinger 1951 6.99

Table 2: Sample Data for Book Table

1. Define the Book Model: Define a SQLAlchemy model for the Book table with the
specified columns and data types, ensuring the id column is set as the primary key.
2. Create the Book Table: After defining the model, use Base.metadata.create_all(engine)
to create the Book table in the SQLite database.
3. Add a New Book Entry: Use a session to add a new Book record with the following
details, then commit the transaction:
• Title: "The Great Gatsby"
• Author: "F. Scott Fitzgerald"
• Published Year: 1925
• Price: 10.99
4. Read and Display All Books: Query the Book table to retrieve all entries and print
each book’s title, author, published_year, and price.
5. Update the Price of a Book: Find the book with the title "The Great Gatsby"
and update its price to 12.99, then commit the change.
6. Delete a Book Entry: Delete the book entry with the title "The Great Gatsby"
from the database and commit the deletion.

5
Winter 2024 Complex Data Types Lab 5

Submission Guidelines
You are required to submit a report that includes your code, a detailed explanation, and the
corresponding output. Rename your report as <StudentID_Lab_1.pdf>.

• Your lab report must be generated in LaTeX. Recommended tool: Overleaf. You can
use some of the available templates in Overleaf.

• Include all code/pseudo code relevant to the lab tasks in the lab report.

• Please provide citations for any claims that are not self-explanatory or commonly
understood.

• It is recommended to use vector graphics (e.g., .pdf, .svg) for all visualizations.

• In cases of high similarities between two reports, both reports will be discarded.

You might also like