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

Schema of Users table in Sqlite.db

Uses PRAGMA statement to read schema.

Describe Schema, here is resource Resource- What is a database schema?

- database blueprint
  • What is the purpose of identity Column in SQL database?
    • to know which data is belong to
  • What is the purpose of a primary key in SQL database?
    • To find the data more much easily also faster
  • What are the Data Types in SQL table?
    • string
import sqlite3

database = 'instance/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()

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? A Connection object represents a unique session with a data source. I think the connection create the relationship to database.
  • Same for cursor object? In this case, cursor connect to the database called sqlite3
  • Look at conn object and cursor object in VSCode debugger. What attributes are in the object?
  • Is "results" an object? How do you know? I don't think result is an object that connect database. This is the value from database
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 users').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()

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? I think sqlite3 is more simple than SQL. In SQL, we have to define all the column, but it is more precise and more comfortable while doing a project.
  • Explain purpose of SQL INSERT. Is this the same as User init? No Insert means to put the data in sqlite3
import sqlite3

def create():
    name = input("Enter your name:")
    uid = input("Enter your user id:")
    password = input("Enter your password")
    dob = input("Enter your date of birth 'YYYY-MM-DD'")
    
    # 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 (_name, _uid, _password, _dob) VALUES (?, ?, ?, ?)", (name, uid, password, dob))
        
        # 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()
    
#create()

Updating a User in table in Sqlite.db

Uses SQL UPDATE to modify password

  • What does the hacked part do? is to change the value in database
  • Explain try/except, when would except occur? if there is and error
  • What code seems to be repeated in each of these examples to point, why is it repeated?
    • cursor.execute, it is the code to manage database
import sqlite3

def 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()

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?
    • because it removes one of data, and it is difficult to redintegrate
  • In the print statemements, what is the "f" and what does {uid} do?
    • f means format, so it will print the value more beautiful
import sqlite3

def 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?
    • Menu has to be repeated because users sometime don't want for only one thing. They sometime want to create and update it.
  • Could you refactor this menu? Make it work with a List?
    • Ok I will.
def menu():
    operation = input("Enter: (C)reate (R)ead (U)pdate or (D)elete or (S)chema")

    if operation.lower() == '1':
        create()
    elif operation.lower() == '2':
        read()
    elif operation.lower() == '3':
        update()
    elif operation.lower() == '4':
        delete()
    elif operation.lower() == '5':
        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")

hack

import requests
import json
url = "https://corona-virus-world-and-india-data.p.rapidapi.com/api"

headers = {
	"X-RapidAPI-Key": "56cf0d9c39msh90ab47fd56c02e6p1d2792jsn0f4dfaa46b90",
	"X-RapidAPI-Host": "corona-virus-world-and-india-data.p.rapidapi.com"
}

response = requests.request("GET", url, headers=headers)

# print(response.text['countries_stat'])

countries = response.json().get('countries_stat')
print(len(countries))
import sqlite3

import requests

def make():
    

    url = "https://corona-virus-world-and-india-data.p.rapidapi.com/api"

    headers = {
        "X-RapidAPI-Key": "56cf0d9c39msh90ab47fd56c02e6p1d2792jsn0f4dfaa46b90",
        "X-RapidAPI-Host": "corona-virus-world-and-india-data.p.rapidapi.com"
    }

    response = requests.request("GET", url, headers=headers)
    countries = response.json().get('countries_stat')
    
    # Connect to the database file
    con = sqlite3.connect('instance/covid.db')

    # Create a cursor object to execute SQL queries
    cur = con.cursor()

    cur.execute('''CREATE TABLE covid
                (country_name, cases, deaths, total_recovered, serious_critical, active_cases)''')

    # Save (commit) the changes
    con.commit()

    # We can also close the connection if we are done with it.
    # Just be sure any changes have been committed or they will be lost.
    con.close()
        
make()
import sqlite3


import requests
def make():
    
    # Connect to the database file
    con = sqlite3.connect('instance/covid.db')

    # Create a cursor object to execute SQL queries
    cur = con.cursor()

    url = "https://corona-virus-world-and-india-data.p.rapidapi.com/api"

    headers = {
        "X-RapidAPI-Key": "56cf0d9c39msh90ab47fd56c02e6p1d2792jsn0f4dfaa46b90",
        "X-RapidAPI-Host": "corona-virus-world-and-india-data.p.rapidapi.com"
    }

    response = requests.request("GET", url, headers=headers)
    countries = response.json().get('countries_stat')

    

    for i in range(len(countries)):
        country_name = countries[i]["country_name"]
        cases = countries[i]["cases"]
        deaths = countries[i]["deaths"]
        total_recovered = countries[i]["total_recovered"]
        serious_critical = countries[i]["serious_critical"]
        active_cases = countries[i]["active_cases"]
        cur.execute("INSERT INTO covid (country_name, cases, deaths, total_recovered, serious_critical, active_cases) VALUES (?, ?, ?, ?, ?, ?)", (country_name, cases, deaths, total_recovered, serious_critical, active_cases))

    # Save (commit) the changes
    con.commit()


    con.close()
        
make()
import sqlite3

def read():
    # Connect to the database file
    conn = sqlite3.connect('instance/playlist.db')

    # 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 playlist').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()
import sqlite3

def create():
    title = input("Enter the song title:")
    author = input("Enter author:")
    link = input("Enter the link")
    whenMade = input("Enter your date of birth 'YYYY-MM-DD'")
    time = input()
    # 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 stock (_name, _uid, _password, _dob) VALUES (?, ?, ?, ?)", (name, uid, password, dob))
        
        # 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()

Create

import sqlite3
def rebuild():
    conn = sqlite3.connect('instance/covid.db')
    cursor = conn.cursor()
import sqlite3

def recreate_covid():
    country_name = input("Enter the country_name: ")
    cases = input("Enter whole cases: ")
    deaths = input("Enter the deaths: ")
    total_recovered = input("Enter total_recovered")
    serious_critical = input("Enter total_recovered")
    active_cases = input("enter the active cases")
    conn = sqlite3.connect('instance/covid.db')
    cursor = conn.cursor()

    try:
        # Execute an SQL command to insert data into a table
        cursor.execute("DELETE INTO covid")
        cursor.execute("INSERT INTO covid (_name, _uid, _password, _dob) VALUES (?, ?, ?, ?)", (country_name, cases, deaths, total_recovered, serious_critical, active_cases))
        
        # Commit the changes to the database
        conn.commit()
        print(f"A new user record {country_name} 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()
recreate_covid()
Error while executing the INSERT: near "INTO": syntax error
import sqlite3
from tabulate import tabulate

def read_covid():
    # Connect to the database file
    conn = sqlite3.connect('instance/covid.db')

    # 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 covid').fetchall()

    # Print the results
    table = tabulate(results, headers=["appName", "_uid", "_password", "_personalUse", "_favoriteFeature"])
    print(table)
    # Close the cursor and connection objects
    cursor.close()
    conn.close()
read_covid()
import sqlite3

def update_covid():
    conn = sqlite3.connect('instance/covid.db')

    cursor = conn.cursor()
    country_name = input("Enter conuntry name for update")

    cases = input('cases')
    

    cursor.execute("SELECT country_name FROM covid where country_name= '"+country_name+"'")
    results = cursor.fetchall()
    if len(results) == 0:
        return "no country"
    else: 
        pass






    try:
        # Execute an SQL command to update data in a table
        cursor.execute("UPDATE covid SET cases = ? WHERE country_name = ?", (cases, country_name))
        if cursor.rowcount == 0:
            # The uid was not found in the table
            print(f"No uid {country_name} was not found in the table")
        else:
            print(f"The row with covid id {country_name} the password has been success")
            conn.commit()
    except sqlite3.Error as error:
        print("Error while executing the UPDATE:", error)
        
    
    # Close the cursor and connection objects
    cursor.close()
    conn.close()
import sqlite3

def delete_covid():
    country_name = input("Enter country to delete")

    # Connect to the database file
    conn = sqlite3.connect('instance/covid.db')

    cursor = conn.cursor()
    
    try:
        cursor.execute("DELETE FROM covid WHERE country_name = ?", (country_name,))
        if cursor.rowcount == 0:
            # The uid was not found in the table
            print(f"No uid {country_name} 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 {country_name} 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_covid()
import sqlite3
def schema_covid():
    conn = sqlite3.connect('instance/covid.db')

    cursor = conn.cursor()
    results = cursor.execute("PRAGMA table_info('covid')").fetchall()
    for row in results:
        print(row)
    cursor.close()
    conn.close()
def menu():
    
    operation = input("Enter: (C)reate (R)ead (U)pdate or (D)elete or (S)chema or E(nd)")
    
    if operation== 'c':
            recreate_covid()
    if operation == 'r':
            read_covid()
    if operation == 'u':
            update_covid()
    if operation == 'd':
            delete_covid()
    if operation == 's':
            schema_covid()
    if len(operation)==0: # Escape Key
            return
    else:
        print("Please enter c, r, u, or d") 
        
try:
    menu() # start menu
except:
    print("Perform Jupyter 'Run All' prior to starting menu")
                        appName     _uid     _password    _personalUse    _favoriteFeature
----------------------  ----------  -------  -----------  --------------  ------------------
Brazil                  30,345,654  662,663  29,364,400   8,318           318,591
France                  28,244,977  145,020  25,852,832   1,677           2,247,125
Germany                 24,109,433  134,624  21,243,000   1,980           2,731,809
UK                      21,933,206  173,352  20,782,350   339             977,504
Russia                  18,137,137  374,902  17,474,628   2,300           287,607
S. Korea                16,895,194  22,133   N/A          726             N/A
Italy                   16,079,209  162,609  14,684,371   409             1,232,229
Turkey                  15,016,270  98,676   14,854,475   975             63,119
Spain                   11,786,036  103,908  11,261,340   339             420,788
Vietnam                 10,563,502  43,013   9,086,075    612             1,434,414
Argentina               9,060,923   128,344  8,895,999    412             36,580
Netherlands             8,035,603   22,206   7,643,520    94              369,877
Japan                   7,621,562   29,284   7,135,403    195             456,875
Iran                    7,216,040   140,975  6,966,954    1,046           108,111
Colombia                6,091,094   139,771  5,924,433    342             26,890
Indonesia               6,043,768   156,067  5,868,251    2,771           19,450
Poland                  5,991,197   115,948  5,334,375    1,588           540,874
Mexico                  5,733,514   324,117  5,033,892    4,798           375,505
Australia               5,689,377   6,991    5,274,197    135             408,189
Ukraine                 4,997,224   108,306  N/A          177             N/A
Malaysia                4,427,067   35,491   4,310,599    89              80,977
Thailand                4,165,874   27,778   3,954,945    1,496           183,151
Austria                 4,104,859   18,047   3,989,860    121             96,952
Israel                  4,054,342   10,658   4,009,152    220             34,532
Belgium                 4,015,791   31,319   3,726,457    169             258,015
Czechia                 3,895,544   40,081   3,838,099    43              17,364
Portugal                3,791,744   22,162   N/A          61              N/A
South Africa            3,759,689   100,298  3,632,572    175             26,819
Canada                  3,695,585   38,777   3,426,082    426             230,726
Philippines             3,684,500   60,182   3,610,658    289             13,660
Switzerland             3,579,867   13,816   3,378,507    90              187,544
Peru                    3,559,343   212,724  N/A          356             N/A
Chile                   3,544,463   57,375   3,368,772    286             118,316
Greece                  3,277,557   28,867   3,151,717    277             96,973
Denmark                 2,959,040   6,072    2,929,091    15              23,877
Romania                 2,888,318   65,427   2,606,660    216             216,231
Sweden                  2,498,388   18,656   2,464,421    19              15,311
Iraq                    2,324,141   25,204   2,295,947    20              2,990
Serbia                  2,001,144   15,953   1,967,786    25              17,405
Bangladesh              1,952,532   29,127   1,893,131    1,297           30,274
Hungary                 1,890,953   46,048   1,776,617    45              68,288
Slovakia                1,774,808   19,839   1,730,712    88              24,257
Jordan                  1,694,216   14,048   1,678,941    124             1,227
Georgia                 1,654,255   16,800   1,635,791    0               1,664
Pakistan                1,527,856   30,369   1,493,998    186             3,489
Ireland                 1,509,536   6,996    1,415,949    41              86,591
Norway                  1,423,509   2,871    N/A          20              N/A
Kazakhstan              1,305,457   13,660   1,290,988    24              809
Hong Kong               1,201,431   9,236    N/A          115             N/A
Singapore               1,180,124   1,325    1,109,387    9               69,412
Morocco                 1,164,670   16,065   1,148,154    293             451
Bulgaria                1,152,892   36,849   959,542      105             156,501
Croatia                 1,117,175   15,778   1,096,829    22              4,568
Cuba                    1,101,486   8,523    1,091,603    23              1,360
Lebanon                 1,096,320   10,374   1,079,455    186             6,491
Lithuania               1,054,618   9,063    1,016,510    31              29,045
Tunisia                 1,039,532   28,533   N/A          29              N/A
Slovenia                1,003,970   6,576    980,501      30              16,893
Finland                 1,000,472   3,638    46,000       31              950,834
Nepal                   978,743     11,951   966,523      0               269
Belarus                 977,434     6,922    928,536      0               41,976
Bolivia                 904,377     21,908   855,123      220             27,346
UAE                     897,136     2,302    879,787      0               15,047
Uruguay                 895,775     7,197    886,654      18              1,924
New Zealand             884,289     636      824,272      0               59,381
Ecuador                 868,053     35,581   N/A          759             N/A
Costa Rica              847,784     8,383    829,515      43              9,886
Guatemala               841,341     17,496   821,185      5               2,660
Latvia                  817,316     5,743    803,135      9               8,438
Azerbaijan              792,476     9,707    782,634      0               135
Panama                  771,486     8,182    759,832      8               3,472
Saudi Arabia            753,332     9,076    740,467      45              3,789
Sri Lanka               663,131     16,502   642,574      0               4,055
Paraguay                649,034     18,795   624,673      5               5,566
Kuwait                  631,294     2,555    627,899      8               840
Myanmar                 612,733     19,434   591,609      0               1,690
Palestine               581,816     5,353    575,899      17              564
Dominican Republic      578,954     4,376    574,297      16              281
Estonia                 570,257     2,531    507,474      7               60,252
Bahrain                 565,830     1,475    560,795      3               3,560
Venezuela               522,121     5,705    515,305      230             1,111
Moldova                 516,986     11,489   504,142      49              1,355
Egypt                   515,645     24,613   442,182      122             48,850
Libya                   501,862     6,429    490,900      101             4,533
Cyprus                  470,481     1,011    124,370      60              345,100
Ethiopia                470,417     7,510    454,967      15              7,940
Mongolia                469,580     2,177    313,256      192             154,147
Armenia                 422,825     8,622    410,558      0               3,645
Honduras                422,275     10,892   131,100      105             280,283
Oman                    388,995     4,257    384,055      2               683
Bosnia and Herzegovina  376,699     15,756   192,218      0               168,725
Réunion                 374,295     742      355,605      10              17,948
Qatar                   364,089     677      362,568      1               844
Kenya                   323,696     5,649    317,909      0               138
Zambia                  318,984     3,974    314,075      0               935
North Macedonia         309,062     9,271    299,064      0               727
Botswana                305,859     2,688    303,026      1               145
Albania                 274,791     3,496    270,869      2               426
Algeria                 265,761     6,874    178,344      6               80,543
Nigeria                 255,685     3,143    249,890      11              2,652
Zimbabwe                247,524     5,468    241,362      12              694
Uzbekistan              238,469     1,637    236,483      23              349
Montenegro              234,619     2,713    231,297      6               609
Luxembourg              233,966     1,058    221,501      1               11,407
Mozambique              225,358     2,201    223,104      13              53
Laos                    205,975     732      7,660        0               197,583
Kyrgyzstan              200,983     2,991    196,386      131             1,606
China                   200,654     4,725    166,398      236             29,531
Iceland                 183,974     112      75,685       1               108,177
Maldives                178,883     298      163,687      25              14,898
Afghanistan             178,689     7,682    161,748      1,124           9,259
Uganda                  164,069     3,596    100,205      2               60,268
El Salvador             162,089     4,127    150,662      8               7,300
Ghana                   161,124     1,445    159,655      1               24
Namibia                 158,332     4,023    153,662      0               647
Martinique              147,519     918      104          8               146,497
Trinidad and Tobago     144,359     3,812    133,604      18              6,943
Brunei                  141,014     218      139,724      2               1,072
Guadeloupe              140,130     854      2,250        19              137,026
Cambodia                136,200     3,056    132,896      0               248
Rwanda                  129,764     1,458    45,522       0               82,784
Jamaica                 129,489     2,943    82,965       0               43,581
Cameroon                119,780     1,927    117,791      13              62
Angola                  99,194      1,900    97,149       0               145
Malta                   90,595      688      84,646       4               5,261
DRC                     87,023      1,337    50,930       0               34,756
Senegal                 85,984      1,966    84,001       1               17
Malawi                  85,747      2,633    81,938       67              1,176
Ivory Coast             81,887      799      81,061       0               27
French Guiana           80,422      394      11,254       1               68,774
Suriname                79,302      1,327    49,396       0               28,579
Channel Islands         73,609      166      72,059       0               1,384
French Polynesia        72,648      648      N/A          7               N/A
Eswatini                70,284      1,397    68,764       11              123
Barbados                67,256      389      63,424       0               3,443
Fiji                    64,524      862      62,677       0               985
Madagascar              64,121      1,391    59,370       14              3,360
Guyana                  63,413      1,228    62,092       1               93
Sudan                   62,093      4,930    N/A          0               N/A
New Caledonia           60,457      312      60,064       9               81
Mauritania              58,683      982      57,693       0               8
Bhutan                  57,771      20       53,080       3               4,671
Belize                  57,419      676      56,534       6               209
Taiwan                  56,468      856      23,729       0               31,883
Cabo Verde              56,004      401      55,538       23              65
Syria                   55,795      3,150    52,090       0               555
Gabon                   47,597      303      47,282       0               12
Papua New Guinea        43,732      649      43,025       7               58
Seychelles              42,079      165      41,260       0               654
Curaçao                 41,966      273      41,251       3               442
Andorra                 41,013      153      40,343       14              517
Burundi                 38,887      38       773          0               38,076
Mauritius               37,656      990      35,656       0               1,010
Mayotte                 37,038      187      2,964        0               33,887
Togo                    36,977      273      36,679       0               25
Guinea                  36,459      440      35,976       8               43
Faeroe Islands          34,658      28       7,693        5               26,937
Aruba                   34,589      212      34,251       2               126
Tanzania                33,864      803      N/A          7               N/A
Bahamas                 33,463      789      32,310       11              364
Lesotho                 32,910      697      24,155       0               8,058
Mali                    30,727      731      29,795       0               201
Haiti                   30,640      835      29,389       0               416
Isle of Man             28,416      87       26,794       0               1,535
Benin                   26,952      163      25,506       5               1,283
Somalia                 26,485      1,350    13,182       0               11,953
Congo                   24,079      385      20,178       0               3,516
Saint Lucia             23,239      368      22,736       1               135
Timor-Leste             22,860      130      22,714       0               16
Cayman Islands          21,755      26       8,553        1               13,176
Burkina Faso            20,853      382      20,439       0               32
Nicaragua               18,491      225      4,225        0               14,041
Gibraltar               17,706      102      16,579       0               1,025
South Sudan             17,422      138      13,514       1               3,770
Tajikistan              17,388      124      17,264       0               0
Liechtenstein           17,103      85       16,831       0               187
San Marino              16,140      114      15,662       4               364
Equatorial Guinea       15,907      183      15,698       5               26
Djibouti                15,611      189      15,411       0               11
CAR                     14,649      113      6,859        2               7,677
Grenada                 14,428      220      13,945       4               263
Bermuda                 13,143      131      12,719       0               293
Solomon Islands         12,437      139      11,194       2               1,104
Dominica                12,011      63       11,926       0               22
Gambia                  11,995      365      11,591       0               39
Greenland               11,971      21       2,761        4               9,189
Yemen                   11,818      2,148    9,001        23              669
Monaco                  11,604      54       11,362       4               188
Saint Martin            10,279      63       1,399        7               8,817
Sint Maarten            9,990       86       9,841        10              63
Eritrea                 9,733       103      9,629        0               1
Caribbean Netherlands   9,592       34       9,392        0               166
Tonga                   9,553       11       8,306        0               1,236
Niger                   8,914       309      8,507        1               98
Guinea-Bissau           8,185       171      7,515        6               499
Comoros                 8,100       160      7,933        0               7
Sierra Leone            7,681       125      N/A          0               N/A
Antigua and Barbuda     7,571       135      7,402        1               34
Liberia                 7,432       294      5,747        2               1,391
Chad                    7,396       193      4,874        0               2,329
Samoa                   7,185       13       1,605        3               5,567
Vanuatu                 6,793       12       5,991        5               790
St. Vincent Grenadines  6,779       106      6,641        0               32
British Virgin Islands  6,296       62       N/A          1               N/A
Sao Tome and Principe   5,953       73       5,875        0               5
Turks and Caicos        5,941       36       5,862        4               43
Saint Kitts and Nevis   5,561       43       5,517        0               1
Cook Islands            4,727       0        3,990        0               737
St. Barth               4,432       6        N/A          0               N/A
Palau                   4,396       6        3,879        1               511
Kiribati                3,076       13       2,597        3               466
Anguilla                2,731       9        2,716        4               6
Saint Pierre Miquelon   2,641       1        2,449        1               191
Diamond Princess        712         13       699          0               0
Wallis and Futuna       454         7        438          0               9
Montserrat              183         2        174          0               7
Falkland Islands        128         0        N/A          0               N/A
Macao                   82          0        82           0               0
Vatican City            29          0        29           0               0
Marshall Islands        15          0        7            0               8
Western Sahara          10          1        9            0               0
MS Zaandam              9           2        7            0               0
Niue                    8           0        7            0               1
Nauru                   3           0        3            0               0
Saint Helena            2           0        2            0               0
Micronesia              1           0        1            0               0
Please enter c, r, u, or d
import sqlite3
 

conn = sqlite3.connect("baseballmarket.db", isolation_level=None)
 

c = conn.cursor()
 

productList = (('baseball','35'),('bat','100'),('glove','150'))
 
c.execute("CREATE TABLE IF NOT EXISTS productList(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, price INTEGER)")
c.execute("CREATE TABLE IF NOT EXISTS orderList(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, cnt INTEGER, price INTEGER, total INTEGER)")

for row in c.execute('SELECT count(*) FROM productList'):
    if row[0] == 0:
        c.executemany("INSERT INTO productList (name,price) values (?,?)", productList)
 
## 상품 목록을 표시하는 코드
while True:
    print("------------------list------------------")
    for row in c.execute('SELECT id,name, price FROM productList'):
        print('number :',row[0],', name :', row[1], ', price :', row[2])
    print("--------------------------------------------")
 
    print('')
    num = input("write the number you want to buy: ")
    c.execute("SELECT name, price FROM productList WHERE id = ?",(num,))
    result = c.fetchone()
 
    print('')
    
    count = int(input("write how much to buy: "))
    total = count * int(result[1])
 
    c.execute("INSERT INTO orderList (name, cnt, price, total) VALUES (?,?,?,?)", (result[0],count,result[1],total))
 
    
    print('')
    print("see the purchase history")
    print("--------------------order list--------------------")
    for row in c.execute('SELECT * FROM orderList'):
        print('name :',row[1],', order number :', row[2], ', unit price :', row[3], ', price :', row[4])
    print("------------------------------------------------")
 
    print('')
    print("Are you gonna buy more?\n\press x to stop\nif you want to continue, press enter ")
    if(input() == "x"): break
 
print('')
print("whole purchase list", end='')
for row in c.execute('SELECT sum(total) FROM orderList'):
    print(' : ',row[0],'dollars')
print('')
 
conn.close()

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.
    • Use Imperative or OOP style to Create a new Table or do something that applies to your CPT project.

Reference... sqlite documentation