VOID
Using Programs with Data is focused on SQL and database actions. Part B focuses on learning SQL commands, connections, and curses using an Imperative programming style,
def create_connection(db_file):
""" create a database connection to the SQLite database
specified by db_file
:param db_file: database file
:return: Connection object or None
"""
conn = None
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
print(e)
return conn
def create_table(conn, create_table_sql):
""" create a table from the create_table_sql statement
:param conn: Connection object
:param create_table_sql: a CREATE TABLE statement
:return:
"""
try:
c = conn.cursor()
c.execute(create_table_sql)
except Error as e:
print(e)
def main():
database = 'instance/test.db'
sql_create_grades_table = """ CREATE TABLE IF NOT EXISTS projects (
id integer PRIMARY KEY,
name text NOT NULL,
begin_date text,
end_date text
); """
# create a database connection
conn = create_connection(database)
# create tables
if conn is not None:
# create tasks table
create_table(conn, sql_create_grades_table)
else:
print("Error! cannot create the database connection.")
Schema
import sqlite3
database = 'instance/test.db'
def schema():
conn = sqlite3.connect(database)
cursor = conn.cursor()
results = cursor.execute("PRAGMA table_info('grades')").fetchall()
for row in results:
print(row)
conn.close()
schema()
Create
import sqlite3
def create():
subject = input("Enter your class:")
grade = input("Enter your letter grade:")
# 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 grades (_subject, _grade) VALUES (?, ?)", (subject, grade))
# Commit the changes to the database
conn.commit()
print(f"A new subject 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()