Advertisement
brendan-stanford

SQL-Read,Write,Update,Delete

Jan 31st, 2020
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. #import libraries
  2. import sqlite3
  3.  
  4. #connect to database
  5. conn = sqlite3.connect("computer_cards.db")
  6.  
  7. #define computer data creation function
  8. def create(name, cores, cpu_speed, ram, cost):
  9. insert_sql = "INSERT INTO computer(name, cores, cpu_speed, ram, cost) VALUES ('{}', {}, {}, {}, {})".format(name, cores, cpu_speed, ram, cost)
  10. conn.execute(insert_sql)
  11. conn.commit()
  12.  
  13. #define computer data update function
  14. def update(name, cores, cpu_speed, ram, cost):
  15. update_sql = "UPDATE computer SET cores = {}, cpu_speed = {}, ram = {}, cost = {} WHERE name = '{}'".format(cores, cpu_speed, ram, cost, name)
  16. conn.execute(update_sql)
  17. conn.commit()
  18.  
  19. #define database read function
  20. def read(name):
  21. select_sql = "SELECT * FROM computer WHERE name = '{}'".format(name)
  22. result = conn.execute(select_sql)
  23. return result.fetchone()
  24.  
  25. #define database delete function
  26. def delete(name):
  27. delete_sql = "DELETE FROM computer WHERE name = '{}'".format(name)
  28. conn.execute(delete_sql)
  29. conn.commit()
  30.  
  31. #choose whether to create, update, delete or read via database
  32. command = input("(C)reate, (U)pdate, (D)elete or (R)ead a card: ")
  33.  
  34. if command == "C":
  35. name = input("Name >")
  36. cores = input("Cores >")
  37. cpu_speed = input("CPU speed (GHz) >")
  38. ram = input("RAM (MB) >")
  39. cost = input("Cost ($) >")
  40.  
  41. create(name, cores, cpu_speed, ram, cost)
  42.  
  43. if command == "U":
  44. name = input("Name >")
  45. cores = input("Cores >")
  46. cpu_speed = input("CPU speed (GHz) >")
  47. ram = input("RAM (MB) >")
  48. cost = input("Cost ($) >")
  49.  
  50. update(name, cores, cpu_speed, ram, cost)
  51.  
  52. elif command == "R":
  53. name = input("Name >")
  54. card = read(name)
  55. print(card)
  56.  
  57. elif command == "D":
  58. name = input("Name >")
  59. delete(name)
  60.  
  61. #close database connection
  62. conn.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement