maroph

db_curd.py

Nov 16th, 2019
290
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.76 KB | None | 0 0
  1. import sqlite3
  2.  
  3.  
  4. class ItemComputer:
  5.     """
  6.    Wrapper class for a record in the table computer
  7.    field names/types of table computer
  8.    name      : text
  9.    cores     : integer
  10.    cpu_speed : real
  11.    ram       : real
  12.    cost      : real
  13.    """
  14.  
  15.     def __init__(self, name='', cores=0, cpu_speed=0, ram=0, cost=0):
  16.         self.__set_name(name)
  17.         self.__set_cores(cores)
  18.         self.__set_cpu_speed(cpu_speed)
  19.         self.__set_ram(ram)
  20.         self.__set_cost(cost)
  21.  
  22.     def __str__(self):
  23.         return "ItemComputer[name:" + self.__name + "|cores:" + str(self.__cores) + \
  24.                "|cpu_speed:" + str(self.__cpu_speed) + \
  25.                "|ram:" + str(self.__ram) + "|cost:" + str(self.__cost) + "]"
  26.  
  27.     def __get_name(self):
  28.         return self.__name
  29.  
  30.     def __set_name(self, name):
  31.         if name is None:
  32.             raise ValueError('None is not a valid value')
  33.         if not isinstance(name, str):
  34.             raise ValueError('wrong type: must be a string')
  35.         self.__name = name
  36.  
  37.     def __get_cores(self):
  38.         return self.__cores
  39.  
  40.     def __set_cores(self, cores):
  41.         if cores is None:
  42.             raise ValueError('None is not a valid value')
  43.         if not isinstance(cores, int):
  44.             cores = int(cores)
  45.         self.__cores = cores
  46.  
  47.     def __get_cpu_speed(self):
  48.         return self.__cpu_speed
  49.  
  50.     def __set_cpu_speed(self, cpu_speed):
  51.         if cpu_speed is None:
  52.             raise ValueError('None is not a valid value')
  53.         if not isinstance(cpu_speed, int):
  54.             cpu_speed = int(cpu_speed)
  55.         self.__cpu_speed = cpu_speed
  56.  
  57.     def __get_ram(self):
  58.         return self.__ram
  59.  
  60.     def __set_ram(self, ram):
  61.         if ram is None:
  62.             raise ValueError('None is not a valid value')
  63.         if not isinstance(ram, int):
  64.             ram = int(ram)
  65.         self.__ram = ram
  66.  
  67.     def __get_cost(self):
  68.         return self.__cost
  69.  
  70.     def __set_cost(self, cost):
  71.         if cost is None:
  72.             raise ValueError('None is not a valid value')
  73.         if not isinstance(cost, int) and not isinstance(cost, float):
  74.             try:
  75.                 cost = int(cost)
  76.             except:
  77.                 try:
  78.                     cost = float(cost)
  79.                 except Exception as e:
  80.                     print(e)
  81.                     raise e
  82.         self.__cost = cost
  83.  
  84.     name = property(__get_name, __set_name)
  85.     cores = property(__get_cores, __set_cores)
  86.     cpu_speed = property(__get_cpu_speed, __set_cpu_speed)
  87.     ram = property(__get_ram, __set_ram)
  88.     cost = property(__get_cost, __set_cost)
  89.  
  90.     def print_item(self):
  91.         print("{:10}: {}".format("name", self.__name))
  92.         print("{:10}: {}".format("cores", self.__cores))
  93.         print("{:10}: {}".format("cpu_speed", self.__cpu_speed))
  94.         print("{:10}: {}".format("ram", self.__ram))
  95.         print("{:10}: {}".format("cost", self.__cost))
  96.  
  97.     def set_item(self, row):
  98.         if not isinstance(row, tuple):
  99.             raise ValueError('list expected')
  100.         self.__set_name("Invalid")
  101.         self.__set_cores(0)
  102.         self.__set_cpu_speed(0)
  103.         self.__set_ram(0)
  104.         self.__set_cost(0)
  105.  
  106.         self.__set_name(row[0])
  107.         self.__set_cores(row[1])
  108.         self.__set_cpu_speed(row[2])
  109.         self.__set_ram(row[3])
  110.         self.__set_cost(row[4])
  111.  
  112.     def fill_item(self, change_name=True):
  113.         if change_name:
  114.             self.__set_name("Invalid")
  115.         self.__set_cores(0)
  116.         self.__set_cpu_speed(0)
  117.         self.__set_ram(0)
  118.         self.__set_cost(0)
  119.  
  120.         print("Enter the details:")
  121.         if change_name:
  122.             while True:
  123.                 resp = input("{0:10}: ".format("name"))
  124.                 resp = resp.strip()
  125.                 try:
  126.                     self.__set_name(resp)
  127.                 except ValueError as e:
  128.                     print(e)
  129.                     continue
  130.                 break
  131.  
  132.         while True:
  133.             resp = input("{0:10}: ".format("cores"))
  134.             resp = resp.strip()
  135.             try:
  136.                 self.__set_cores(resp)
  137.             except Exception as e:
  138.                 print(e)
  139.                 continue
  140.             break
  141.  
  142.         while True:
  143.             resp = input("{0:10}: ".format("cpu_speed"))
  144.             resp = resp.strip()
  145.             try:
  146.                 self.__set_cpu_speed(resp)
  147.             except Exception as e:
  148.                 print(e)
  149.                 continue
  150.             break
  151.  
  152.         while True:
  153.             resp = input("{0:10}: ".format("ram"))
  154.             resp = resp.strip()
  155.             try:
  156.                 self.__set_ram(resp)
  157.             except Exception as e:
  158.                 print(e)
  159.                 continue
  160.             break
  161.  
  162.         while True:
  163.             resp = input("{0:10}: ".format("cost"))
  164.             resp = resp.strip()
  165.             try:
  166.                 self.__set_cost(resp)
  167.             except Exception as e:
  168.                 print(e)
  169.                 continue
  170.             break
  171.  
  172.  
  173. def item_create():
  174.     conn = sqlite3.connect("computer_cards.db")
  175.  
  176.     item = ItemComputer()
  177.     item.fill_item()
  178.  
  179.     sql = "INSERT INTO computer(name, cores, cpu_speed, ram, cost) VALUES ('{}', {}, {}, {}, {})".format(
  180.           item.name, item.cores, item.cpu_speed, item.ram, item.cost)
  181.     print("SQL:>>>>>" + sql + "<<<<<")
  182.     conn.execute(sql)
  183.     conn.commit()
  184.     conn.close()
  185.  
  186.  
  187. def item_read(name):
  188.     conn = sqlite3.connect("computer_cards.db")
  189.     sql = "SELECT * FROM computer WHERE name = '{}'".format(name)
  190.     print("SQL:>>>>>" + sql + "<<<<<")
  191.     result = conn.execute(sql)
  192.     row = result.fetchone()
  193.     if row is None:
  194.         print("no item found with name {}".format(name))
  195.         return
  196.     item = ItemComputer()
  197.     item.set_item(row)
  198.     print("Current values of item {}".format(name))
  199.     item.print_item()
  200.     conn.close()
  201.  
  202. def item_update(name):
  203.     conn = sqlite3.connect("computer_cards.db")
  204.     sql = "SELECT * FROM computer WHERE name = '{}'".format(name)
  205.     print("SQL:>>>>>" + sql + "<<<<<")
  206.     result = conn.execute(sql)
  207.     row = result.fetchone()
  208.     if row is None:
  209.         print("no item found with name {}".format(name))
  210.         return
  211.     item = ItemComputer()
  212.     item.set_item(row)
  213.     print("Current values of item {}".format(name))
  214.     item.print_item()
  215.     item.fill_item(change_name=False)
  216.     sql = "UPDATE computer SET cores = {}, cpu_speed = {}, ram = {}, cost = {} WHERE name = '{}'".format(
  217.           item.cores, item.cpu_speed, item.ram, item.cost, name)
  218.     print("SQL:>>>>>" + sql + "<<<<<")
  219.     cursor = conn.cursor()
  220.     cursor.execute(sql)
  221.     print("SQL updated items:", cursor.rowcount)
  222.     cursor.close()
  223.     conn.commit()
  224.     conn.close()
  225.  
  226. def item_delete(name):
  227.     conn = sqlite3.connect("computer_cards.db")
  228.     cursor = conn.cursor()
  229.     sql = "DELETE FROM computer WHERE name = '{}'".format(name)
  230.     print("SQL:>>>>>" + sql + "<<<<<")
  231.     cursor.execute(sql)
  232.     print("SQL deleted items:", cursor.rowcount)
  233.     if cursor.rowcount < 1:
  234.         print("no item found with name '{}'".format(name))
  235.     if cursor.rowcount > 1:
  236.         print("{} items with name '{}' deleted".format(cursor.rowcount, name))
  237.     cursor.close()
  238.     conn.commit()
  239.     conn.close()
  240.  
  241. def item_list_all():
  242.     conn = sqlite3.connect("computer_cards.db")
  243.     result = conn.execute("SELECT * FROM computer ORDER BY name")
  244.     computers = result.fetchall()
  245.  
  246.     for computer in computers:
  247.         item = ItemComputer()
  248.         item.set_item(computer)
  249.         item.print_item()
  250.         print("--------------------")
  251.  
  252.     conn.close()
  253.  
  254.  
  255. while True:
  256.     action = input("Action: Create, Read, Update, Delete, List, Quit[c/r/u/d/l/q]: ")
  257.     if action not in ["C","c","R","r","U","u","D","d","L","l","Q","q"]:
  258.         print("Unknown action")
  259.         continue;
  260.     if action in ["Q","q"]:
  261.         break
  262.     if action in ["C", "c"]:
  263.         item_create()
  264.         continue
  265.     if action in ["R", "r"]:
  266.         while True:
  267.             name = input("Give name of item to read:")
  268.             if len(name) == 0:
  269.                 continue
  270.             break
  271.         item_read(name)
  272.         continue
  273.     if action in ["U", "u"]:
  274.         while True:
  275.             name = input("Give name of item to update:")
  276.             if len(name) == 0:
  277.                 continue
  278.             break
  279.         item_update(name)
  280.         continue
  281.     if action in ["D", "d"]:
  282.         while True:
  283.             name = input("Give name of item to delete:")
  284.             if len(name) == 0:
  285.                 continue
  286.             break
  287.         item_delete(name)
  288.         continue
  289.     if action in ["L", "l"]:
  290.         print("Print content of table computer")
  291.         item_list_all()
  292.         continue
Advertisement
Add Comment
Please, Sign In to add comment