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/sqlite3.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('players')").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)', 0, None, 0)
(2, '_team', 'VARCHAR(255)', 0, None, 0)
(3, '_position', 'INTEGER', 0, None, 0)
(4, '_likes', 'INTEGER', 0, None, 0)
(5, '_dislikes', 'INTEGER', 0, None, 0)
(6, '_comments', 'BLOB', 0, None, 0)
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 players').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, 'Ike Anigbogu', 'Indiana Pacers', 'C', 1, 1, b"\x80\x05\x957\x00\x00\x00\x00\x00\x00\x00]\x94}\x94(\x8c\x04name\x94\x8c\nDontavious\x94\x8c\x07message\x94\x8c\x0eYou're trash!!\x94ua.")
(2, 'Ron Baker', 'New York Knicks', 'G', 20, 0, b'\x80\x05\x950\x00\x00\x00\x00\x00\x00\x00]\x94}\x94(\x8c\x04name\x94\x8c\nDontavious\x94\x8c\x07message\x94\x8c\x07Mid tbh\x94ua.')
(3, 'Jabari Bird', 'Boston Celtics', 'G', 3, 0, b'\x80\x05\x95Z\x00\x00\x00\x00\x00\x00\x00]\x94}\x94(\x8c\x04name\x94\x8c\nDontavious\x94\x8c\x07message\x94\x8c13.0/3.0: Great job! You deserve some seed points.\x94ua.')
(4, 'MarShon Brooks', 'Memphis Grizzlies', 'G', 2, 0, b'\x80\x05]\x94.')
(6, '', '', '', 0, 0, None)
(7, 'Jamal', 'Jamal', 'Jamal', 0, 0, None)
(8, '', '', '', 0, 0, None)
(9, '', '', '', 0, 0, None)

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

from sqlalchemy import PickleType

def create():
    player_name = input("Enter a player name: ")
    team_name = input("Enter the player's team name: ")
    position = input("Enter the player's position: ")
    
    # 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 players (_name, _team, _position, _likes, _dislikes) VALUES (?, ?, ?, ?, ?)", (player_name, team_name, position, 0, 0))
        
        # Commit the changes to the database
        conn.commit()
        print(f"A new user record {player_name} 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 Quintillion 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 updateLikes():
    pid = input("Enter player ID to update: ")
    likes = input("Enter new likes: ")
    
    # 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 players SET _likes = ? WHERE id = ?", (pid, likes))
        if cursor.rowcount == 0:
            # The uid was not found in the table
            print(f"No uid {pid} was not found in the table")
        else:
            print(f"The row with user id {pid} has the new likes: {likes}")
            conn.commit()
    except sqlite3.Error as error:
        print("Error while executing the UPDATE:", error)
    
    # Close the cursor and connection objects
    cursor.close()
    conn.close()

def updateDislikes():
    pid = input("Enter player ID to update: ")
    dislikes = input("Enter new dislikes: ")
    
    # 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 players SET _dislikes = ? WHERE id = ?", (pid, dislikes))
        if cursor.rowcount == 0:
            # The uid was not found in the table
            print(f"No uid {pid} was not found in the table")
        else:
            print(f"The row with user id {pid} has the new dislikes: {dislikes}")
            conn.commit()
    except sqlite3.Error as error:
        print("Error while executing the UPDATE:", error)
        
    # Close the cursor and connection objects
    cursor.close()
    conn.close()

updateLikes()
updateDislikes()
No uid 1 was not found in the table
No uid 2 was not found in the table

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():
    pid = 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 players WHERE id = ?", (pid))
        if cursor.rowcount == 0:
            # The uid was not found in the table
            print(f"No id {pid} was not found in the table")
        else:
            # The uid was found in the table and the row was deleted
            print(f"The row with id {pid} 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()
    
The row with id 4 was successfully deleted

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() == 'ul':
        updateLikes()
    elif operation.lower() == 'ud':
        updateDislikes()
    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")
(1, 'Ike Anigbogu', 'Indiana Pacers', 'C', 0, 20, b"\x80\x05\x957\x00\x00\x00\x00\x00\x00\x00]\x94}\x94(\x8c\x04name\x94\x8c\nDontavious\x94\x8c\x07message\x94\x8c\x0eYou're trash!!\x94ua.")
(2, 'Ron Baker', 'New York Knicks', 'G', 20, 0, b'\x80\x05\x950\x00\x00\x00\x00\x00\x00\x00]\x94}\x94(\x8c\x04name\x94\x8c\nDontavious\x94\x8c\x07message\x94\x8c\x07Mid tbh\x94ua.')
(3, 'Jabari Bird', 'Boston Celtics', 'G', 3, 0, b'\x80\x05\x95Z\x00\x00\x00\x00\x00\x00\x00]\x94}\x94(\x8c\x04name\x94\x8c\nDontavious\x94\x8c\x07message\x94\x8c13.0/3.0: Great job! You deserve some seed points.\x94ua.')
(4, 'MarShon Brooks', 'Memphis Grizzlies', 'G', 0, 0, b'\x80\x05]\x94.')
A new user record mugsy boegs has been created
(1, 'Ike Anigbogu', 'Indiana Pacers', 'C', 0, 20, b"\x80\x05\x957\x00\x00\x00\x00\x00\x00\x00]\x94}\x94(\x8c\x04name\x94\x8c\nDontavious\x94\x8c\x07message\x94\x8c\x0eYou're trash!!\x94ua.")
(2, 'Ron Baker', 'New York Knicks', 'G', 20, 0, b'\x80\x05\x950\x00\x00\x00\x00\x00\x00\x00]\x94}\x94(\x8c\x04name\x94\x8c\nDontavious\x94\x8c\x07message\x94\x8c\x07Mid tbh\x94ua.')
(3, 'Jabari Bird', 'Boston Celtics', 'G', 3, 0, b'\x80\x05\x95Z\x00\x00\x00\x00\x00\x00\x00]\x94}\x94(\x8c\x04name\x94\x8c\nDontavious\x94\x8c\x07message\x94\x8c13.0/3.0: Great job! You deserve some seed points.\x94ua.')
(4, 'MarShon Brooks', 'Memphis Grizzlies', 'G', 0, 0, b'\x80\x05]\x94.')
(5, 'mugsy boegs', 'hornets', 'PG', 0, 0, None)
The row with id 5 was successfully deleted
(1, 'Ike Anigbogu', 'Indiana Pacers', 'C', 0, 20, b"\x80\x05\x957\x00\x00\x00\x00\x00\x00\x00]\x94}\x94(\x8c\x04name\x94\x8c\nDontavious\x94\x8c\x07message\x94\x8c\x0eYou're trash!!\x94ua.")
(2, 'Ron Baker', 'New York Knicks', 'G', 20, 0, b'\x80\x05\x950\x00\x00\x00\x00\x00\x00\x00]\x94}\x94(\x8c\x04name\x94\x8c\nDontavious\x94\x8c\x07message\x94\x8c\x07Mid tbh\x94ua.')
(3, 'Jabari Bird', 'Boston Celtics', 'G', 3, 0, b'\x80\x05\x95Z\x00\x00\x00\x00\x00\x00\x00]\x94}\x94(\x8c\x04name\x94\x8c\nDontavious\x94\x8c\x07message\x94\x8c13.0/3.0: Great job! You deserve some seed points.\x94ua.')
(4, 'MarShon Brooks', 'Memphis Grizzlies', 'G', 0, 0, b'\x80\x05]\x94.')
  • Describe Schema, here is resource Resource- What is a database schema?
    • This queries and returns the database in question
    • What is the purpose of identity Column in SQL database?
      • To find a column of data within a SQLDatabase
    • What is the purpose of a primary key in SQL database?
      • Easily identifies a row of data
    • What are the Data Types in SQL table?
      • SQLAlchemy library Objects of different primitive types
  • What is a connection object? After you google it, what do you think it does?
    • Instantionates a connection to the database
  • Same for cursor object?
    • the cursor object allows you to edit the databse through means of its methods
  • Look at conn object and cursor object in VSCode debugger. What attributes are in the object?
    • The attributes are x, y, z and etc
  • Is "results" an object? How do you know?
    • no, results is a dictionary. I know because i checked the debugger
  • Compore create() in both SQL lessons. What is better or worse in the two implementations?
    • THis is more difficult as you don't craete an object and instead have to create a request
  • Explain purpose of SQL INSERT. Is this the same as User init?
    • This is a type of request that allows you to do tangs