Unit 2.4b Using Programs with Data, SQLAlchemy
Using Programs with Data is focused on SQL and database actions. Part A focuses on SQLAlchemy and an OOP programming style,
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
- Explore SQLite Connect object to establish database connection- Explore SQLite Cursor Object to fetch data from a table within a database
Schema of Users table in Sqlite.db
Uses PRAGMA statement to read schema.
Describe Schema, here is resource Resource- What is a database schema?
- It defines how the data is organized and how it can be accessed and modified by users and applications.
- What is the purpose of identity Column in SQL database?
- It can be used as a primary key or as a reference in foreign keys to establish relationships between tables.
- What is the purpose of a primary key in SQL database?
- It ensures that no two rows have the same values in the primary key column, and it can be used as a reference in foreign keys to establish relationships between tables.
- What are the Data Types in SQL table?
- Common data types include integer, real, text, and blob, and each has a specific range of values and storage requirements.
import sqlite3
database = 'instance/hw.db' # this is location of database
def hw_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('homework')").fetchall()
# Print the results
for row in results:
print(row)
# Close the database connection
conn.close()
hw_schema()
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?
- It provides methods for connecting to a database, executing SQL statements, and managing transactions.
- Same for cursor object?
- It provides methods for navigating the result set, fetching rows, and executing SQL statements.
- Look at conn object and cursor object in VSCode debugger. What attributes are in the object?
- Connection object:- database: the name of the connected database - user: the name of the user used to connect to the database
- host: the name of the host or IP address of the database server
- port: the port number used to connect to the database server
- Cursor object:
- description: a list of tuples that describes the columns in the current result set
- rowcount: the number of rows affected by the last SQL statement
- Connection object:- database: the name of the connected database - user: the name of the user used to connect to the database
- Is "results" an object? How do you know?
- Yes because it has attriubutes
import sqlite3
def hw_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 homework').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()
# hw_read()
import sqlite3
def hw_create():
Teacher = input("Enter your name: Ms/Mr (blank)")
uid = input("Enter your user id:")
homework = input("Enter the homework")
# 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 hw (_name, _uid, _homework) VALUES (?, ?, ?)", (Teacher, uid, homework))
# 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()
# hw_create()
import sqlite3
def hw_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()
import sqlite3
def hw_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?
- recursion
- Could you refactor this menu? Make it work with a List?
- To refactor the menu and make it work with a list, you could define a list of tuples that map each operation to a function, like this:
def menu():
options = ['c', 'r', 'u', 'd', 's']
operation = input("Enter: (C)reate (R)ead (U)pdate or (D)elete or (S)chema")
operation = operation.lower()
if operation in options:
index = options.index(operation)
functions = [hw_create, hw_read, hw_update, hw_delete, hw_schema]
functions[index]()
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")
def menu():
operation = input("Enter: (C)reate (R)ead (U)pdate or (D)elete or (S)chema")
if operation.lower() == 'c':
hw_create()
elif operation.lower() == 'r':
hw_read()
elif operation.lower() == 'u':
hw_update()
elif operation.lower() == 'd':
hw_delete()
elif operation.lower() == 's':
hw_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 this implementation, do you see procedural abstraction?
- In 2.4a or 2.4b lecture
- Do you see data abstraction? Complement this with Debugging example.
- If you debug the menu, and step into one of the hw_functions, it will show the code for them, which abstracts more code itself
- Use Imperative or OOP style to Create a new Table or do something that applies to your CPT project.
- Do you see data abstraction? Complement this with Debugging example.
Reference... sqlite documentation