☰
Python Across Disciplines
with Python + AI Tool   
×
Table of Contents

1.1.   Introduction 1.2.   About the Author & Contact Info 1.3.   Book Conventions 1.4.   What (Who) is a Programmer? 1.5.   Programming Across Disciplines 1.6.   Foundational Computing Concepts 1.7.   About Python 1.8.   First Steps 1.8.1 Computer Setup 1.8.2 Python print() Function 1.8.3 Comments
2.1. About Data 2.2. Data Types 2.3. Variables 2.4. User Input 2.5. Data Structures (DS)         2.5.1. DS Concepts         2.5.2. Lists         2.5.3. Dictionaries         2.5.4. Others 2.6. Files         2.6.1. Files & File Systems         2.6.2. Python File Object         2.6.3. Data Files 2.7. Databases
3.1. About Processing 3.2. Decisions         3.2.1 Decision Concepts         3.2.2 Conditions & Booleans         3.2.3 if Statements         3.2.4 if-else Statements         3.2.5 if-elif-else Statements         3.2.6 In-Line if Statements 3.3. Repetition (a.k.a. Loops)         3.3.1  Repetition Concepts         3.3.2  while Loops         3.3.3  for Loops         3.3.4  Nested Loops         3.3.5  Validating User Input 3.4. Functions         3.4.1  Function Concepts         3.4.2  Built-In Functions         3.4.3  Programmer Defined Functions 3.5. Libraries         3.5.1  Library Concepts         3.5.2  Standard Library         3.5.3  External Libraries 3.6. Processing Case Studies         3.6.1  Case Studies         3.6.2  Parsing Data
4.1. About Output 4.2. Advanced Printing 4.3. Data Visualization   4.4  Sound
  4.5  Graphics
  4.6  Video
  4.7  Web Output
  4.8  PDFs & Documents
  4.9  Dashboards
  4.10  Animation & Games
  4.11  Text to Speech

5.1 About Disciplines 5.2 Accounting 5.3 Architecture 5.4 Art 5.5 Artificial Intelligence (AI) 5.6 Autonomous Vehicles 5.7 Bioinformatics 5.8 Biology 5.9 Bitcoin 5.10 Blockchain 5.11 Business 5.12 Business Analytics 5.13 Chemistry 5.14 Communication 5.15 Computational Photography 5.16 Computer Science 5.17 Creative Writing 5.18 Cryptocurrency 5.19 Cultural Studies 5.20 Data Analytics 5.21 Data Engineering 5.22 Data Science 5.23 Data Visualization 5.24 Drone Piloting 5.25 Economics 5.26 Education 5.27 Engineering 5.28 English 5.29 Entrepreneurship 5.30 Environmental Studies 5.31 Exercise Science 5.32 Film 5.33 Finance 5.34 Gaming 5.35 Gender Studies 5.36 Genetics 5.37 Geography 5.38 Geology 5.39 Geospatial Analysis ☯ 5.40 History 5.41 Humanities 5.42 Information Systems 5.43 Languages 5.44 Law 5.45 Linguistics 5.46 Literature 5.47 Machine Learning 5.48 Management 5.49 Marketing 5.50 Mathematics 5.51 Medicine 5.52 Military 5.53 Model Railroading 5.54 Music 5.55 Natural Language Processing (NLP) 5.56 Network Analysis 5.57 Neural Networks 5.58 Neurology 5.59 Nursing 5.60 Pharmacology 5.61 Philosophy 5.62 Physiology 5.63 Politics 5.64 Psychiatry 5.65 Psychology 5.66 Real Estate 5.67 Recreation 5.68 Remote Control (RC) Vehicles 5.69 Rhetoric 5.70 Science 5.71 Sociology 5.72 Sports 5.73 Stock Trading 5.74 Text Mining 5.75 Weather 5.76 Writing
6.1. Databases         6.1.1 Overview of Databases         6.1.2 SQLite Databases         6.1.3 Querying a SQLite Database         6.1.4 CRUD Operations with SQLite         6.1.5 Connecting to Other Databases
Built-In Functions Conceptss Data Types Date & Time Format Codes Dictionary Methods Escape Sequences File Access Modes File Object Methods Python Keywords List Methods Operators Set Methods String Methods Tuple Methods Glossary Index Appendices   Software Install & Setup
  Coding Tools:
  A.  Python    B.  Google CoLaboratory    C.  Visual Studio Code    D.  PyCharm IDE    E.  Git    F.  GitHub 
  Database Tools:
  G.  SQLite Database    H.  MySQL Database 


Python Across Disciplines
by John Gordon © 2023

Table of Contents

Table of Contents  »  Chapter 6.1.4 : CRUD Operations w/SQLite

CRUD Operations w/SQLite
Subscribe Contact


Contents

Overview

On the previous page we explored querying a database from within Python. In many forms of software development, we perform what is known as CRUD Operations with databases. CRUD stands for Create, Read, Update and Delete. These operations are so common that it is often assumed programmers know how to do them, not only in SQL but also in general purpose programming languages like Java, Python, C#, C++, etc. CRUD are the operations that we use to query a database, add new data to a database, update (change) data that exists in a database, and delete from a database, as needed. On this page we will explore inserting, updating and deleting data in a database.

CRUD Operations

In a production system databases are central to storing and maintaining data. The following diagram depicts an example of a web business that takes orders over the internet through a website. The website interacts with the company's database when customers create their accounts, place orders, etc. The employees of the company that operates the website also interact with the database to detect new orders, conduct financial and shipping steps, manage customer accounts, etc.



Figure 1: CRUD Operations

Each interaction with the database is part of CRUD operations. Here are a few examples using the above scenario:

Each of these actions are coded by a programmer to make the operations possible.



Terminology

The acronym CRUD refers to the actions (operations) of creating, reading, updating, and deleting data from a database. CRUD is used in many contexts, not just in SQL programming. In different contexts, the actual commands used to perform those actions are a little different. Here are the equivalent SQL commands that correspond with CRUD actions.

Operation SQL Command
Create INSERT
Read SELECT
Update UPDATE
Delete DELETE


Inserting (Adding) Records

The SQL INSERT command is used to add (insert) records (rows) to tables in our database. There are three general forms of SQL INSERT syntax as shown here:

Form 1:
INSERT INTO table_name (Column, Column, Column, ...)
VALUES (value, value, value, ...);

...this form will insert a row into table_name with the specified column(s) being populated by the specified value(s) in the VALUES list. This is particularly useful when you are inserting rows and only populating a subset of the table's attributes, not all of them.

Form 2:
INSERT INTO table_name
VALUES (value, value, value, value, value, value, value);

...this form is used when you are going to insert the row and populate every column in the table. Caution should be used with this form if the target table contains any autoincrementing attributes which are populated automatically by the database engine. Attempting to include a value for an autoincrementing attribute in an insert statement will cause an error.

Form 3:
INSERT INTO table_name (Column, Column, Column, ...) VALUES
(value, value, value, ...),
(value, value, value, ...),
(value, value, value, ...),
(value, value, value, ...),
(value, value, value, ...),
(value, value, value, ...),
(value, value, value, ...);

... this form is used when you want to insert multiple rows at one time. You specify the columns list once, and then a series of value statements, separated by commas. The very last value statement gets the semicolon to complete the statement. Note: This form can also be used in conjunction with Form 2 if you are populating every column in the table.

Example

To see how to use INSERT in Python, let's take a look at some example code that demonstrates a couple of different approaches to running embedded INSERT statements in Python. In this example we'll re-use the simple query to SELECT all students with the last name Cooper that we used previously.

Code
import sqlite3

def print_report():
  print("-" * 60)
  print("ID\t\tName\t\tClass\tGPA")
  print("-" * 60)
  for row in cursor:
    print (row[4] + "\t" + row[1] + " " + row[2] + "\t" + row[3] + "\t" + str(row[5]))
  print("-" * 60)

# Main

sql_report = """SELECT * FROM students WHERE last_name = 'Cooper'
    ORDER BY last_name, first_name;"""
sql_dynamic = ""

conn = sqlite3.connect('C:\SQLite\Data\grading_system.db')

print ("\nInitial List of 'Cooper' Students:")
cursor = conn.execute(sql_report)
print_report()

# Hardcoded INSERT example
sql_dynamic = """INSERT INTO students (first_name, last_name,
    class_standing, school_id, cumulative_gpa,
    major_id) VALUES ('Zachary', 'Cooper',
    'Junior', 'S77777777', 3.0, 11)"""
conn.execute(sql_dynamic)
conn.commit()

print ("Hardcoded INSERT Result:")
cursor = conn.execute(sql_report)
print_report()

# Dynamic INSERT example
print ("\nUser Prompts for New Student Record: ")
first_name = input("First Name: ")
last_name = input("Last Name: ")
class_standing = input("Class Standing: ")
school_id = input("School ID: ")
cumulative_gpa = input("Cumulative GPA: ")
major_id = input("Major ID: ")
sql_dynamic = "INSERT INTO students (first_name, last_name, "
sql_dynamic += "class_standing, school_id, cumulative_gpa, "
sql_dynamic += "major_id) VALUES ('" + first_name + "', '"
sql_dynamic += last_name + "', '" + class_standing + "', '"
sql_dynamic += school_id + "'," + str(cumulative_gpa) + ","
sql_dynamic += str(major_id) + ");"
conn.execute(sql_dynamic)
conn.commit()

print("\n")
print ("Dynamic INSERT Result:")
cursor = conn.execute(sql_report)
print_report()

conn.close()
Output
nitial List of 'Cooper' Students:
------------------------------------------------------------
ID              Name            Class   GPA
------------------------------------------------------------
S35743296       Kendra Cooper   Senior  4
S40063558       Patricia Cooper Senior  4
------------------------------------------------------------
Hardcoded INSERT Result:
------------------------------------------------------------
ID              Name            Class   GPA
------------------------------------------------------------
S35743296       Kendra Cooper   Senior  4
S40063558       Patricia Cooper Senior  4
S77777777       Zachary Cooper  Junior  3
------------------------------------------------------------

User Prompts for New Student Record:
First Name: Bob
Last Name: Cooper
Class Standing: Freshman
School ID: S99999999
Cumulative GPA: 3.5
Major ID: 11


Dynamic INSERT Result:
------------------------------------------------------------
ID              Name            Class   GPA
------------------------------------------------------------
S99999999       Bob Cooper      Freshman        3.5
S35743296       Kendra Cooper   Senior  4
S40063558       Patricia Cooper Senior  4
S77777777       Zachary Cooper  Junior  3
------------------------------------------------------------
Notes


Updating (Changing) Records

In SQL we use the UPDATE command to modify ("edit") existing records in our database.

The general form of UPDATE specifies the table to be updated, the SET clause, the attributes (fields) and their new values, and (almost always) the WHERE clause.

UPDATE table_name SET column = value, column = value, ... WHERE condition;

Note: WHERE clause filtering is critical when using the UPDATE statement in SQL. When updating records in a database, we rarely want to update (change) all records with the same value(s). This is the source of some fairly common and very damaging mistakes that occur when using UPDATE. It is very important to realize that an UPDATE statement without a WHERE clause will make the specified changes to every record in the table.

Example

To see how to use UPDATE in Python, let's use the data we worked with in the INSERT statement example above to take a look at some example code that demonstrates a couple of different approaches to running embedded UPDATE statements in Python.

Code
Output
Notes


Deleting Records

To see how to use DELETE in Python, .........

Code
Output
Notes








© 2023 John Gordon
Cascade Street Publishing, LLC