Database Programming is Program with Data

The Tri 2 Final Project is 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?

- The columns of a database aka the information that populates the datatable.
  • What is the purpose of identity Column in SQL database?
    • The purpose is to have unique rows of data and to be able to differentiate different users.
  • What is the purpose of a primary key in SQL database?
    • The primary key has to be unique because it is used as an identifier for different people. For example, name would not be a good primary key because two people could have the same name.
  • What are the Data Types in SQL table?
    • Strings, integers, boolean, images
import sqlite3

database = 'files/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?
    • Each open SQLite database is represented by a Connection object, which is created using sqlite3.connect() . Their main purpose is creating Cursor objects, and Transaction control.
  • Same for cursor object?
    • Simplifies the code for the user. an instance using which you can invoke methods that execute SQLite statements, fetch data from the result sets of the queries.
  • Look at conn object and cursor object in VSCode debugger. What attributes are in the object?
    • The cursor object contains attributes like special variables, function variables, and class variables
    • Conn object contains attributes like special variables and function variables
  • Is "results" an object? How do you know?
    • Results is an object because it has attributes
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 Car').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(Car)
---------------------------------------------------------------------------
OperationalError                          Traceback (most recent call last)
/mnt/c/Users/Sarah Liu/vscode/Sarah-Liu/_notebooks/2023-03-16-AP-unit2-4b.ipynb Cell 6 in <cell line: 24>()
     <a href='vscode-notebook-cell://wsl%2Bubuntu/mnt/c/Users/Sarah%20Liu/vscode/Sarah-Liu/_notebooks/2023-03-16-AP-unit2-4b.ipynb#W5sdnNjb2RlLXJlbW90ZQ%3D%3D?line=20'>21</a>     cursor.close()
     <a href='vscode-notebook-cell://wsl%2Bubuntu/mnt/c/Users/Sarah%20Liu/vscode/Sarah-Liu/_notebooks/2023-03-16-AP-unit2-4b.ipynb#W5sdnNjb2RlLXJlbW90ZQ%3D%3D?line=21'>22</a>     conn.close()
---> <a href='vscode-notebook-cell://wsl%2Bubuntu/mnt/c/Users/Sarah%20Liu/vscode/Sarah-Liu/_notebooks/2023-03-16-AP-unit2-4b.ipynb#W5sdnNjb2RlLXJlbW90ZQ%3D%3D?line=23'>24</a> read()

/mnt/c/Users/Sarah Liu/vscode/Sarah-Liu/_notebooks/2023-03-16-AP-unit2-4b.ipynb Cell 6 in read()
      <a href='vscode-notebook-cell://wsl%2Bubuntu/mnt/c/Users/Sarah%20Liu/vscode/Sarah-Liu/_notebooks/2023-03-16-AP-unit2-4b.ipynb#W5sdnNjb2RlLXJlbW90ZQ%3D%3D?line=7'>8</a> cursor = conn.cursor()
     <a href='vscode-notebook-cell://wsl%2Bubuntu/mnt/c/Users/Sarah%20Liu/vscode/Sarah-Liu/_notebooks/2023-03-16-AP-unit2-4b.ipynb#W5sdnNjb2RlLXJlbW90ZQ%3D%3D?line=9'>10</a> # Execute a SELECT statement to retrieve data from a table
---> <a href='vscode-notebook-cell://wsl%2Bubuntu/mnt/c/Users/Sarah%20Liu/vscode/Sarah-Liu/_notebooks/2023-03-16-AP-unit2-4b.ipynb#W5sdnNjb2RlLXJlbW90ZQ%3D%3D?line=10'>11</a> results = cursor.execute('SELECT * FROM Car').fetchall()
     <a href='vscode-notebook-cell://wsl%2Bubuntu/mnt/c/Users/Sarah%20Liu/vscode/Sarah-Liu/_notebooks/2023-03-16-AP-unit2-4b.ipynb#W5sdnNjb2RlLXJlbW90ZQ%3D%3D?line=12'>13</a> # Print the results
     <a href='vscode-notebook-cell://wsl%2Bubuntu/mnt/c/Users/Sarah%20Liu/vscode/Sarah-Liu/_notebooks/2023-03-16-AP-unit2-4b.ipynb#W5sdnNjb2RlLXJlbW90ZQ%3D%3D?line=13'>14</a> if len(results) == 0:

OperationalError: no such table: Car

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?
    • Out of the two create(), the sqlite3 method using conn and cur is better. It is able to accomplish the same thing with less code while being less complicated and just as efficient.
  • Explain purpose of SQL INSERT. Is this the same as User init?
    • SQL INSERT is a command used to add new records or rows of data to a database table
    • User init is a method used in object-oriented programming languages like Python. The init method is used to initialize the properties or attributes of an object when it is created.
import sqlite3

def create():
    brand = "Enter your Brand"
    color = "Enter your color"
    powersource = "Enter your powersource"
    type = "Enter your type"
    
    # 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 (_brand, _color, _powersource, _type) VALUES (Lexus, black, electric, coupe)", (brand, color, powersource, type))
        
        # Commit the changes to the database
        conn.commit()
        print(f"A new user record {Car} 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?
    • It serves like a warning message. When the length of my password is less than 2, the message will appear.
  • Explain try/except, when would except occur?
    • Except would occur if there is a sqlite3 error
  • What code seems to be repeated in each of these examples to point, why is it repeated?
    • cursor = conn.cursor() is repeated in each example. Most likely because this line of code is necessary to connect to the database
import sqlite3

def update():
    new_brand = input("Enter updated brand:")
    new_color = input("Enter updated color:")
    new_powersource = input("Enter updated powersource:")
    new_type = input("Enter updated type:")

    # 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 car {car} was not found in the table")
        else:
            print(f"The row with car {car} 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?
    • When you perform a delete operation on a SQLite database, you are permanently removing data from the database. If you accidentally delete the wrong data or forget to include a WHERE clause in your delete statement, you can end up losing valuable data.
  • What is the "f" and {uid} do?
    • {uid} gets the uid of the user in question
    • "f" is the syntax for formatted string literals. Inside this string, you can write a Python expression between { } characters that can refer to variables or literal values.
import sqlite3

def delete():
    brand = input("Enter brand:")
    color = input("Enter color:")
    powersource = input("Enter powersource:")
    type = input("Enter type:")

    # 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 _brand = ? WHERE _color = ? WHERE _powersource = ? WHERE _type = ?" (brand, color, powersource, type))
        if cursor.rowcount == 0:
            # The uid was not found in the table
            print(f"No car {car} was not found in the table")
        else:
            # The uid was found in the table and the row was deleted
            print(f"The row with car {car} 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?
    • As the function continues, it calls itself, thus the menu is always repeating
  • Could you refactor this menu? Make it work with a List?
    • Yes its better to refactor this menu since recursion can lead to stack overflow.
def menu():
    operation = input("Enter: (C)reate (R)ead (U)pdate or (D)elete or (S)chema")
    if operation.lower() == 'c':
        create()
    # i clicked on r and it gave me the database
    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")

Hacks

  • Add this Blog to you own Blogging site. In the Blog add notes and observations on each code cell.
  • In 2.4a or 2.4b lecture: Do you see data abstraction?

Yes. For example, the class User is an example of data abstraction. it initializes multiple objects with several parameters. It would be very hard to save properties of a user into a database if they were not all comprised into one object. Thus, in this sense, the data is abstracted