Database Programming is Program with Data

Each Tri 2 Final Project should be an example of a Program with Data.

Prepare to use SQLite in common Imperative Technique

Schema of Users table in Sqlite.db

Uses PRAGMA statement to read schema.

Describe Schema, here is resource Resource- What is a database schema?

  • What is the purpose of identity Column in SQL database?
  • What is the purpose of a primary key in SQL database?
  • What are the Data Types in SQL table?
import sqlite3

database = 'instance/sqlite.db' # this is location of database

def schema():
    
    # Connect to the database file
    conn = sqlite3.connect(database)

    # Create a cursor object to execute SQL queries
    cursor = conn.cursor()
    
    # Fetch results of Schema
    results = cursor.execute("PRAGMA table_info('users')").fetchall()

    # Print the results
    for row in results:
        print(row)

    # Close the database connection
    conn.close()
    
schema()
(0, 'id', 'INTEGER', 1, None, 1)
(1, '_name', 'VARCHAR(255)', 1, None, 0)
(2, '_uid', 'VARCHAR(255)', 1, None, 0)
(3, '_password', 'VARCHAR(255)', 1, None, 0)
(4, '_dob', 'DATE', 0, None, 0)

Reading Users table in Sqlite.db

Uses SQL SELECT statement to read data

  • What is a connection object? After you google it, what do you think it does?
  • Same for cursor object?
  • Look at conn object and cursor object in VSCode debugger. What attributes are in the object?
  • Is "results" an object? How do you know?
import sqlite3

def read():
    # Connect to the database file
    conn = sqlite3.connect(database)

    # Create a cursor object to execute SQL queries
    cursor = conn.cursor()
    
    # Execute a SELECT statement to retrieve data from a table
    results = cursor.execute('SELECT * FROM users').fetchall()

    # Print the results
    if len(results) == 0:
        print("Table is empty")
    else:
        for row in results:
            print(row)

    # Close the cursor and connection objects
    cursor.close()
    conn.close()
    
read()
(1, 'Thomas Edison', 'toby', 'sha256$8Bjxw79Ppdz33Gu0$f44e29c684011657a48688356e64bf6a0792fcf7b8025af8037a309c941f5e25', '1847-02-11')
(2, 'Nikola Tesla', 'niko', 'sha256$xPVKZBh9zCovm8vq$1353313ea114e70b04119f5381c59f5efc3de90f864eba0dba202c1d4a29a88d', '2023-03-15')
(3, 'Alexander Graham Bell', 'lex', 'sha256$9nbobJ0A7L0cvFtV$5dff2dde113799310d2ad38cbcb02f6869add306561e698b357d9233d80beb0c', '2023-03-15')
(4, 'Eli Whitney', 'whit', 'sha256$mypuMBkTUsTmeLyp$8c797753a2194632490569af3a998b7f7a79e5b74afce647377aab3000e24022', '2023-03-15')
(5, 'Indiana Jones', 'indi', 'sha256$tulHsOl9MApGQI2W$8c03f0a32653c54a41f91d7fe33f274b382e0e8c53957fc08b4892a389951446', '1920-10-21')
(6, 'Marion Ravenwood', 'raven', 'sha256$LU4lrM4WAWJJmb2n$139a6d06746ce0b2fccdc3537d737904a92e6007172fa84bcf87fee29192f1d9', '1921-10-21')
(7, '', '', 'sha256$CIp9RlVgIc0GaqM4$51ef5faaf0fe5a9b6b20a8eb4575e6d5610a844cf37de5a7b4c6ba4b5a3b0a69', '2023-03-15')
(8, 'amay', 'papercuber', 'monkeyboy1234', '2006-o6-10')
(9, 'amay', 'papercubef', 'sha256$PQqiR7p1rxkJHlyP$359deba7daae86afdd05e90ccab3d2e88574c8941fc55673b31118b1bedc2cae', '2006-06-10')

Create a new User in table in Sqlite.db

Uses SQL INSERT to add row

  • Compore create() in both SQL lessons. What is better or worse in the two implementations?
  • Explain purpose of SQL INSERT. Is this the same as User init?
import sqlite3

def create():
    name = input("Enter your name:")
    uid = input("Enter your user id:")
    password = input("Enter your password")
    dob = input("Enter your date of birth 'YYYY-MM-DD'")
    
    # Connect to the database file
    conn = sqlite3.connect(database)

    # Create a cursor object to execute SQL commands
    cursor = conn.cursor()

    try:
        # Execute an SQL command to insert data into a table
        cursor.execute("INSERT INTO users (_name, _uid, _password, _dob) VALUES (?, ?, ?, ?)", (name, uid, password, dob))
        
        # Commit the changes to the database
        conn.commit()
        print(f"A new user record {uid} has been created")
                
    except sqlite3.Error as error:
        print("Error while executing the INSERT:", error)


    # Close the cursor and connection objects
    cursor.close()
    conn.close()
    
create()
A new user record 1904196 has been created

Updating a User in table in Sqlite.db

Uses SQL UPDATE to modify password

  • What does the hacked part do?
  • Explain try/except, when would except occur?
  • What code seems to be repeated in each of these examples to point, why is it repeated?
import sqlite3

def update():
    uid = input("Enter user id to update")
    password = input("Enter updated password")
    if len(password) < 2:
        message = "hacked"
        password = 'gothackednewpassword123'
    else:
        message = "successfully updated"

    # Connect to the database file
    conn = sqlite3.connect(database)

    # Create a cursor object to execute SQL commands
    cursor = conn.cursor()

    try:
        # Execute an SQL command to update data in a table
        cursor.execute("UPDATE users SET _password = ? WHERE _uid = ?", (password, uid))
        if cursor.rowcount == 0:
            # The uid was not found in the table
            print(f"No uid {uid} was not found in the table")
        else:
            print(f"The row with user id {uid} the password has been {message}")
            conn.commit()
    except sqlite3.Error as error:
        print("Error while executing the UPDATE:", error)
        
    
    # Close the cursor and connection objects
    cursor.close()
    conn.close()
    
update()
The row with user id 1904196 the password has been successfully updated

Delete a User in table in Sqlite.db

Uses a delete function to remove a user based on a user input of the id.

  • Is DELETE a dangerous operation? Why?
  • In the print statemements, what is the "f" and what does {uid} do?
import sqlite3

def delete():
    uid = input("Enter user id to delete")

    # Connect to the database file
    conn = sqlite3.connect(database)

    # Create a cursor object to execute SQL commands
    cursor = conn.cursor()
    
    try:
        cursor.execute("DELETE FROM users WHERE _uid = ?", (uid,))
        if cursor.rowcount == 0:
            # The uid was not found in the table
            print(f"No uid {uid} was not found in the table")
        else:
            # The uid was found in the table and the row was deleted
            print(f"The row with uid {uid} was successfully deleted")
        conn.commit()
    except sqlite3.Error as error:
        print("Error while executing the DELETE:", error)
        
    # Close the cursor and connection objects
    cursor.close()
    conn.close()
    
#delete()

Menu Interface to CRUD operations

CRUD and Schema interactions from one location by running menu. Observe input at the top of VSCode, observe output underneath code cell.

  • Why does the menu repeat?
  • Could you refactor this menu? Make it work with a List?
def menu():
    operation = input("Enter: (C)reate (R)ead (U)pdate or (D)elete or (S)chema")
    if operation.lower() == 'c':
        create()
    elif operation.lower() == 'r':
        read()
    elif operation.lower() == 'u':
        update()
    elif operation.lower() == 'd':
        delete()
    elif operation.lower() == 's':
        schema()
    elif len(operation)==0: # Escape Key
        return
    else:
        print("Please enter c, r, u, or d") 
    menu() # recursion, repeat menu
        
try:
    menu() # start menu
except:
    print("Perform Jupyter 'Run All' prior to starting menu")
Please enter c, r, u, or d
A new user record 12345 has been created

Hacks

  • Add this Blog to you own Blogging site. In the Blog add notes and observations on each code cell.
  • In this implementation, do you see procedural abstraction?
  • In 2.4a or 2.4b lecture
    • Do you see data abstraction? Complement this with Debugging example.
    • Use Imperative or OOP style to Create a new Table or do something that applies to your CPT project.

Reference... sqlite documentation

import sqlite3

# Connect to the database
conn = sqlite3.connect('albums.db')

# Create a cursor object to execute SQL commands
c = conn.cursor()

# Create the table if it doesn't exist
c.execute('''
          CREATE TABLE IF NOT EXISTS albums (
              id INTEGER PRIMARY KEY AUTOINCREMENT,
              title TEXT NOT NULL,
              artist TEXT NOT NULL,
              year INTEGER NOT NULL
          )
          ''')

# Define a function to add a new album to the table
def add_album(title, artist, year):
    c.execute("INSERT INTO albums (title, artist, year) VALUES (?, ?, ?)", (title, artist, year))
    conn.commit()

# Define a function to update an existing album in the table
def update_album(album_id, title=None, artist=None, year=None):
    # Create a list of tuples containing the column name and new value for each provided parameter
    updates = [(col, val) for col, val in [("title", title), ("artist", artist), ("year", year)] if val is not None]
    
    update_query = ", ".join([f"{col} = ?" for col, _ in updates])
    
    # Create a list of values to replace the placeholders in the query string
    update_params = [val for _, val in updates] + [album_id]
    
    # Execute the UPDATE query with the new values and commit the changes
    c.execute(f"UPDATE albums SET {update_query} WHERE id = ?", update_params)
    conn.commit()


# Define a function to delete an album from the table
def delete_album(album_id):
    c.execute("DELETE FROM albums WHERE id = ?", (album_id,))
    conn.commit()

# Define a function to retrieve a list of all albums in the table
def get_all_albums():
    c.execute("SELECT * FROM albums")
    return c.fetchall()

def delete_all(table_name):
    de = 'DELETE FROM ' + 'albums.db' + ';'
    conn.execute(de)
    conn.commit()



# Example usage of the functions
#add_album("DAMN", "Kendrick Lamar", 2017)
#add_album("808s and Heartbreak", "Kanye West", 2008)
#add_album("The Melodic Blue", "Baby Keem", 2019)
delete_album(49)

get_all_albums()
[(15, 'The Melodic Blue', 'Baby Keem', 2019),
 (16, 'DAMN', 'Kendrick Lamar', 2017),
 (17, '808s and Heartbreak', 'Kanye West', 2008),
 (18, 'The Melodic Blue', 'Baby Keem', 2019),
 (19, 'DAMN', 'Kendrick Lamar', 2017),
 (20, '808s and Heartbreak', 'Kanye West', 2008),
 (21, 'The Melodic Blue', 'Baby Keem', 2019),
 (22, 'DAMN', 'Kendrick Lamar', 2017),
 (23, '808s and Heartbreak', 'Kanye West', 2008),
 (24, 'The Melodic Blue', 'Baby Keem', 2019),
 (25, 'DAMN', 'Kendrick Lamar', 2017),
 (26, '808s and Heartbreak', 'Kanye West', 2008),
 (27, 'The Melodic Blue', 'Baby Keem', 2019),
 (28, 'DAMN', 'Kendrick Lamar', 2017),
 (29, '808s and Heartbreak', 'Kanye West', 2008),
 (30, 'The Melodic Blue', 'Baby Keem', 2019),
 (31, 'DAMN', 'Kendrick Lamar', 2017),
 (32, '808s and Heartbreak', 'Kanye West', 2008),
 (33, 'The Melodic Blue', 'Baby Keem', 2019),
 (34, 'DAMN', 'Kendrick Lamar', 2017),
 (35, '808s and Heartbreak', 'Kanye West', 2008),
 (37, 'DAMN', 'Kendrick Lamar', 2017),
 (38, '808s and Heartbreak', 'Kanye West', 2008),
 (39, 'The Melodic Blue', 'Baby Keem', 2019),
 (40, 'DAMN', 'Kendrick Lamar', 2017),
 (41, '808s and Heartbreak', 'Kanye West', 2008),
 (42, 'The Melodic Blue', 'Baby Keem', 2019),
 (43, 'DAMN', 'Kendrick Lamar', 2017),
 (44, '808s and Heartbreak', 'Kanye West', 2008),
 (45, 'The Melodic Blue', 'Baby Keem', 2019),
 (46, 'DAMN', 'Kendrick Lamar', 2017),
 (47, '808s and Heartbreak', 'Kanye West', 2008),
 (48, 'The Melodic Blue', 'Baby Keem', 2019)]