Creating the Table

Cell for creating the table

CRUD

This database stores planes and their stats, it implements CRUD using imperative programming

Create

Importing the necessary modules and create function:

import sqlite3

database = 'sqlite.db'


def create_design(designation, price, max_speed, designe):
    conn = sqlite3.connect(database)
    c = conn.cursor()
    
    try:
        # Execute an SQL command to insert data into a table
        c.execute("INSERT INTO cars (designation, price, max_speed) VALUES (?, ?, ?, ?)",
              (designation, price, max_speed))
                
        # Commit the changes to the database
        conn.commit()
        print(f"A new user record {designation} has been created with the data:")
        print((designation, price, max_speed))
                
    except sqlite3.Error as error:
        print("Error while executing the INSERT:", error)

    c.close()
    conn.close()
    
    
create_design("Tesla 2022 model 3", 38999, 162, "Lockheed")
Error while executing the INSERT: no such table: cars

This function takes four arguments (designation, price, max_speed, and designer) and inserts them into the "designs" table as a new record.

Read

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

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

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

    # Close the cursor and connection objects
    c.close()
    conn.close()
    
read_design(1)
---------------------------------------------------------------------------
OperationalError                          Traceback (most recent call last)
/home/haoxuan/vscode/FastProject2/_notebooks/2023-03-16-database-example.ipynb Cell 6 in <cell line: 23>()
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/haoxuan/vscode/FastProject2/_notebooks/2023-03-16-database-example.ipynb#W4sdnNjb2RlLXJlbW90ZQ%3D%3D?line=19'>20</a>     c.close()
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/haoxuan/vscode/FastProject2/_notebooks/2023-03-16-database-example.ipynb#W4sdnNjb2RlLXJlbW90ZQ%3D%3D?line=20'>21</a>     conn.close()
---> <a href='vscode-notebook-cell://wsl%2Bubuntu/home/haoxuan/vscode/FastProject2/_notebooks/2023-03-16-database-example.ipynb#W4sdnNjb2RlLXJlbW90ZQ%3D%3D?line=22'>23</a> read_design(1)

/home/haoxuan/vscode/FastProject2/_notebooks/2023-03-16-database-example.ipynb Cell 6 in read_design(id)
      <a href='vscode-notebook-cell://wsl%2Bubuntu/home/haoxuan/vscode/FastProject2/_notebooks/2023-03-16-database-example.ipynb#W4sdnNjb2RlLXJlbW90ZQ%3D%3D?line=5'>6</a> c = conn.cursor()
      <a href='vscode-notebook-cell://wsl%2Bubuntu/home/haoxuan/vscode/FastProject2/_notebooks/2023-03-16-database-example.ipynb#W4sdnNjb2RlLXJlbW90ZQ%3D%3D?line=7'>8</a> # Execute a SELECT statement to retrieve data from a table
----> <a href='vscode-notebook-cell://wsl%2Bubuntu/home/haoxuan/vscode/FastProject2/_notebooks/2023-03-16-database-example.ipynb#W4sdnNjb2RlLXJlbW90ZQ%3D%3D?line=8'>9</a> results = c.execute('SELECT * FROM cars').fetchall()
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/haoxuan/vscode/FastProject2/_notebooks/2023-03-16-database-example.ipynb#W4sdnNjb2RlLXJlbW90ZQ%3D%3D?line=10'>11</a> # Print the results
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/haoxuan/vscode/FastProject2/_notebooks/2023-03-16-database-example.ipynb#W4sdnNjb2RlLXJlbW90ZQ%3D%3D?line=11'>12</a> if len(results) == 0:

OperationalError: no such table: cars

This function takes a design ID as an argument and returns the record from the "designs" table that matches that ID.

Update

def update_design(design_id, designation=None, price=None, max_speed=None):
    conn = sqlite3.connect(database)
    c = conn.cursor()
    update_dict = {}
    
    if designation is not None:
        update_dict["designation"] = designation
    if price is not None:
        update_dict["price"] = price
    if max_speed is not None:
        update_dict["max_speed"] = max_speed
        
    update_str = ", ".join([f"{col}=? " for col in update_dict.keys()])
    c.execute(f"UPDATE cars SET {update_str} WHERE id=?", (*update_dict.values(), design_id))
    conn.commit()
    print(read_design(design_id))
    
    c.close()
    conn.close()
    
update_design(2, None, None, 498)
---------------------------------------------------------------------------
OperationalError                          Traceback (most recent call last)
/home/haoxuan/vscode/FastProject2/_notebooks/2023-03-16-database-example.ipynb Cell 8 in <cell line: 21>()
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/haoxuan/vscode/FastProject2/_notebooks/2023-03-16-database-example.ipynb#W6sdnNjb2RlLXJlbW90ZQ%3D%3D?line=17'>18</a>     c.close()
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/haoxuan/vscode/FastProject2/_notebooks/2023-03-16-database-example.ipynb#W6sdnNjb2RlLXJlbW90ZQ%3D%3D?line=18'>19</a>     conn.close()
---> <a href='vscode-notebook-cell://wsl%2Bubuntu/home/haoxuan/vscode/FastProject2/_notebooks/2023-03-16-database-example.ipynb#W6sdnNjb2RlLXJlbW90ZQ%3D%3D?line=20'>21</a> update_design(2, None, None, 498)

/home/haoxuan/vscode/FastProject2/_notebooks/2023-03-16-database-example.ipynb Cell 8 in update_design(design_id, designation, price, max_speed)
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/haoxuan/vscode/FastProject2/_notebooks/2023-03-16-database-example.ipynb#W6sdnNjb2RlLXJlbW90ZQ%3D%3D?line=10'>11</a>     update_dict["max_speed"] = max_speed
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/haoxuan/vscode/FastProject2/_notebooks/2023-03-16-database-example.ipynb#W6sdnNjb2RlLXJlbW90ZQ%3D%3D?line=12'>13</a> update_str = ", ".join([f"{col}=? " for col in update_dict.keys()])
---> <a href='vscode-notebook-cell://wsl%2Bubuntu/home/haoxuan/vscode/FastProject2/_notebooks/2023-03-16-database-example.ipynb#W6sdnNjb2RlLXJlbW90ZQ%3D%3D?line=13'>14</a> c.execute(f"UPDATE cars SET {update_str} WHERE id=?", (*update_dict.values(), design_id))
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/haoxuan/vscode/FastProject2/_notebooks/2023-03-16-database-example.ipynb#W6sdnNjb2RlLXJlbW90ZQ%3D%3D?line=14'>15</a> conn.commit()
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/haoxuan/vscode/FastProject2/_notebooks/2023-03-16-database-example.ipynb#W6sdnNjb2RlLXJlbW90ZQ%3D%3D?line=15'>16</a> print(read_design(design_id))

OperationalError: no such table: cars

This function takes a design ID and any combination of the other four arguments as keyword arguments. It updates the record in the "designs" table that matches the ID with the new values provided.

Delete

def delete_design(design_id):
    conn = sqlite3.connect(database)
    c = conn.cursor()
    
    print(read_design(design_id))
    c.execute("DELETE FROM planes WHERE id=?", (design_id,))
    
    conn.commit()
    conn.close()
    
delete_design(2)
---------------------------------------------------------------------------
OperationalError                          Traceback (most recent call last)
/home/haoxuan/vscode/FastProject2/_notebooks/2023-03-16-database-example.ipynb Cell 10 in <cell line: 11>()
      <a href='vscode-notebook-cell://wsl%2Bubuntu/home/haoxuan/vscode/FastProject2/_notebooks/2023-03-16-database-example.ipynb#X11sdnNjb2RlLXJlbW90ZQ%3D%3D?line=7'>8</a>     conn.commit()
      <a href='vscode-notebook-cell://wsl%2Bubuntu/home/haoxuan/vscode/FastProject2/_notebooks/2023-03-16-database-example.ipynb#X11sdnNjb2RlLXJlbW90ZQ%3D%3D?line=8'>9</a>     conn.close()
---> <a href='vscode-notebook-cell://wsl%2Bubuntu/home/haoxuan/vscode/FastProject2/_notebooks/2023-03-16-database-example.ipynb#X11sdnNjb2RlLXJlbW90ZQ%3D%3D?line=10'>11</a> delete_design(2)

/home/haoxuan/vscode/FastProject2/_notebooks/2023-03-16-database-example.ipynb Cell 10 in delete_design(design_id)
      <a href='vscode-notebook-cell://wsl%2Bubuntu/home/haoxuan/vscode/FastProject2/_notebooks/2023-03-16-database-example.ipynb#X11sdnNjb2RlLXJlbW90ZQ%3D%3D?line=1'>2</a> conn = sqlite3.connect(database)
      <a href='vscode-notebook-cell://wsl%2Bubuntu/home/haoxuan/vscode/FastProject2/_notebooks/2023-03-16-database-example.ipynb#X11sdnNjb2RlLXJlbW90ZQ%3D%3D?line=2'>3</a> c = conn.cursor()
----> <a href='vscode-notebook-cell://wsl%2Bubuntu/home/haoxuan/vscode/FastProject2/_notebooks/2023-03-16-database-example.ipynb#X11sdnNjb2RlLXJlbW90ZQ%3D%3D?line=4'>5</a> print(read_design(design_id))
      <a href='vscode-notebook-cell://wsl%2Bubuntu/home/haoxuan/vscode/FastProject2/_notebooks/2023-03-16-database-example.ipynb#X11sdnNjb2RlLXJlbW90ZQ%3D%3D?line=5'>6</a> c.execute("DELETE FROM planes WHERE id=?", (design_id,))
      <a href='vscode-notebook-cell://wsl%2Bubuntu/home/haoxuan/vscode/FastProject2/_notebooks/2023-03-16-database-example.ipynb#X11sdnNjb2RlLXJlbW90ZQ%3D%3D?line=7'>8</a> conn.commit()

/home/haoxuan/vscode/FastProject2/_notebooks/2023-03-16-database-example.ipynb Cell 10 in read_design(id)
      <a href='vscode-notebook-cell://wsl%2Bubuntu/home/haoxuan/vscode/FastProject2/_notebooks/2023-03-16-database-example.ipynb#X11sdnNjb2RlLXJlbW90ZQ%3D%3D?line=5'>6</a> c = conn.cursor()
      <a href='vscode-notebook-cell://wsl%2Bubuntu/home/haoxuan/vscode/FastProject2/_notebooks/2023-03-16-database-example.ipynb#X11sdnNjb2RlLXJlbW90ZQ%3D%3D?line=7'>8</a> # Execute a SELECT statement to retrieve data from a table
----> <a href='vscode-notebook-cell://wsl%2Bubuntu/home/haoxuan/vscode/FastProject2/_notebooks/2023-03-16-database-example.ipynb#X11sdnNjb2RlLXJlbW90ZQ%3D%3D?line=8'>9</a> results = c.execute('SELECT * FROM cars').fetchall()
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/haoxuan/vscode/FastProject2/_notebooks/2023-03-16-database-example.ipynb#X11sdnNjb2RlLXJlbW90ZQ%3D%3D?line=10'>11</a> # Print the results
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/haoxuan/vscode/FastProject2/_notebooks/2023-03-16-database-example.ipynb#X11sdnNjb2RlLXJlbW90ZQ%3D%3D?line=11'>12</a> if len(results) == 0:

OperationalError: no such table: cars

This function takes a design ID as an argument and deletes the record from the "designs" table that matches that ID.

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")
Perform Jupyter 'Run All' prior to starting menu