Advertisement
johnpentyrch

mycrud.py

May 18th, 2020
301
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.27 KB | None | 0 0
  1. import sqlite3
  2. conn = sqlite3.connect("computer_cards.db")
  3. def create(name, cores, cpu_speed,ram,cost):
  4.     insert_sql = "INSERT INTO computer(name, cores, cpu_speed,ram,cost) VALUES ('{}', {}, {}, {}, {})".format(name, cores, cpu_speed,ram,cost)
  5.  
  6.     conn.execute(insert_sql)
  7.  
  8. def read(name):
  9.     select_sql = "SELECT * FROM computer WHERE name = '{}'".format(name)
  10.     result = conn.execute(select_sql)
  11.     ##NB we use fetchone instead of fetchall see previous Returns single row or None if no data
  12.     return result.fetchone()
  13.  
  14. def update(name, cores, cpu_speed,ram,cost):
  15.     card_update = "UPDATE computer SET cores = {}, cpu_speed = {}, ram = {}, cost = {} WHERE name = '{}'".format(cores, cpu_speed, ram, cost, name)
  16.     conn.execute(card_update)
  17.     conn.commit()
  18.  
  19. def delete(name):
  20.     delete_sql = "DELETE FROM computer WHERE name = '{}'".format(name)
  21.     print(delete_sql)
  22.     conn.execute(delete_sql)
  23.     conn.commit()
  24.  
  25.  
  26.  
  27. while True:    
  28.     command = input("(C)reate,   (R)ead a card, (U)pdate a card or (D)elete  >>> ")
  29.     command=command.upper()
  30.     print(command)
  31.     if command == "C":
  32.         name = input("Name >")
  33.         cores = input("Cores >")
  34.         cpu_speed = input("CPU speed (GHz) >")
  35.         ram = input("RAM (MB) >")
  36.         cost = input("Cost ($) >")
  37.         create(name, cores, cpu_speed, ram, cost)
  38.         card=read(name)
  39.         print('Card created ', card)
  40.  
  41.     elif command == "R":
  42.         name = input("Name >")
  43.         card = read(name)
  44.         if card is None:
  45.             print('Card not found')
  46.         else:
  47.             print(card)
  48.  
  49.     elif command == "D":
  50.         name = input("Name >")
  51.         card = read(name)
  52.         if card is None:
  53.             print('Card not found: not deleted')
  54.         else:
  55.             delete(name)
  56.             card = read(name)
  57.             if card is None:
  58.                 print('Deleted')
  59.             else: print('Not deleted; duplicate??')
  60.     elif command == "U":
  61.         name = input("Name >")
  62.         cores = input("Cores >")
  63.         cpu_speed = input("CPU speed (GHz) >")
  64.         ram = input("RAM (MB) >")
  65.         cost = input("Cost ($) >")
  66.         update(name, cores, cpu_speed, ram, cost)
  67.         card=read(name)
  68.         print('Card updated ', card)
  69.  
  70.  
  71. conn.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement