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?

A database schema (short for schematic) is the template for database info to be stored.

  • What is the purpose of identity Column in SQL database? An identity column in SQL, makes it easy to identify objects.
  • What is the purpose of a primary key in SQL database? The primary key is used to uniquely label/identify rows in teh table.
  • What are the Data Types in SQL table? string, numeric, id, etc/
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 dat

  • What is a connection object? After you google it, what do you think it does?

    A connection object is an object that can be used to connect to a file.

  • Same for cursor object?

    A cursor object is a sort of container that denotes when the data editing starts/

  • Look at conn object and cursor object in VSCode debugger. What attributes are in the object?

    A conn object is a term used to denote a "connection object." A Connection object represents a unique session with a data source.

  • Is "results" an object? How do you know?

    Yes, results is an object. I know this since it has variables and functions.

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$NzCfNht1gXt5Uom5$658dbafc78d122d6938bd1070b097c78cff0f6f3d59ee63bed60dfa1b48399e4', '1847-02-11')
(2, 'Nikola Tesla', 'niko', 'sha256$sgmYj9ulUs4dhY8R$e584a772fe4654bf53b86a6c4137c9273c701ec7fe01c8c972547848d238eaa4', '2023-03-16')
(3, 'Alexander Graham Bell', 'lex', 'sha256$k7lkXNTTmHGAIDL7$7f94423366d708917846833b03f4a654454ad70304f57625424826dde0b828c1', '2023-03-16')
(4, 'Eli Whitney', 'whit', 'sha256$PIVG6DVEGpMWUC8z$05f028b5c3e28adc71d6ceeef5b28234c05d1c5336cd9059951c27b14fec4026', '2023-03-16')
(5, 'Indiana Jones', 'indi', 'sha256$sH7OM19apxko13Dd$36bb430a66721b061ee60a6356a755588c003b6387194db101545b691ac46e73', '1920-10-21')
(6, 'Marion Ravenwood', 'raven', 'sha256$zud5X30kSB59aAf8$3b2b155c4dac5f7630b9a026e2069970c68c915c80fb0f2683b04f8b2e51f373', '1921-10-21')
(7, 'hi', '33', 'sha256$WrMNqo2Sc8XVaZMb$e4066655ea2ebfb76378dc655d24457248e4c742da5f9ffa9d2a02b335790a59', '2023-03-16')
(8, 'haseeb', '1123', 'hhees', '2001-09-111')
(9, 'yee', 'y223', 'deeznuts331', '1111-01-01')

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? The object-based create() is most likely better for UI implementation, while the imperative-based create() is most likely better for easy testing.
  • Explain purpose of SQL INSERT. Is this the same as User init? SQL INSERT is a more direct input of the data (I think.) User init is most likely re-instantiating the database, but just with the new data, rather than inputting the data straigth in.
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()

Updating a User in table in Sqlite.db

Uses SQL UPDATE to modify password

  • What does the hacked part do? The hacked part automatically fills in the required information with template information.
  • Explain try/except, when would except occur? Try/except is a conditional statement, sort of like if/else, however rather then checking for a previous requirement, it runs the code under try, and if it doesn't meet the proper requriements, it goes to the except section.
  • What code seems to be repeated in each of these examples to point, why is it repeated? The code for connecting to the database and opening the cursor seems to be repeated. This is because these steps are necessary for accessing db files remotely.
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()

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? Delete is a dangerous operation because it has the potential to remove too much or too little. Also you cannot undo deleted records.
  • In the print statemements, what is the "f" and what does {uid} do? The f{} stuff is known as a formatted string. It basically makes it so that data stored in something like a variable is formatted into a string in a clean manner.
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? The menu would repeat because it has to run thorugh all 5 operations, it's basic recursion.
  • Could you refactor this menu? Make it work with a List? In theory, you could. You would have to make it work on indexes.
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")
No uid 2 was not found in the table

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.

      I see data abstraction throughout these lesssons.

    • Use Imperative or OOP style to Create a new Table or do something that applies to your CPT project.

Reference... sqlite documentation