Advertisement
Fahim999

Database code

Nov 12th, 2019
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.38 KB | None | 0 0
  1. try:
  2.     import sqlite3                                      #This imports the "sqlite3" lib
  3.     chand = sqlite3.connect("computer_cards.db")        #This sets a connectivity handler to the d/B
  4. except:
  5.     print('******************************')
  6.     print('ERROR! Database does not exit!')
  7.     print('Will quit.Goodbye')
  8.     print('******************************')
  9.     quit()
  10.  
  11. def create_new(name, cores, speed, ram, cost):      #This creates a new function called "create_new" with 5 parameters
  12.  
  13.     insert_sql = "INSERT INTO computer(name, cores, cpu_speed, ram, cost) VALUES ('{}', {}, {},{},{})".format(name, cores, speed, ram, cost)
  14.     #The format method then replaces the {} markers in the SQL statement with the values from the 5 variables.
  15.  
  16.     chand.execute(insert_sql)
  17.     chand.commit()                                  #The code then needs to execute the insert_sql statement and commit the changes to the database
  18.  
  19. #This code prompts the user for the new database record
  20. print('')
  21. print('Please enter a new record, with all 5 attributes')
  22. print('')
  23. name = input('Name > ')
  24. cores = input('Cores > ')
  25. speed = input('Speed > ')
  26. ram = input('RAM > ')
  27. cost = input('Cost > ')
  28.  
  29. create_new(name, cores, speed, ram, cost)
  30.  
  31. #This part simply calls the "create_new" function and passes in "Fahim2" and 3
  32. #print('')
  33. #print('We want to add a new record...')
  34. #print('')
  35.  
  36. #create_new("Fahim2", 3)
  37. #print('')
  38.  
  39. #################################################################
  40. # This part of the program just lists the data from the database.
  41. #################################################################
  42.  
  43. result = chand.execute("SELECT * FROM computer")    #This puts the query response into "result" cursor
  44.  
  45. computer_data = result.fetchall()                   #This puts the data from the above SQL in "computer_data
  46.  
  47. print('')
  48. print('The data table contains:')
  49. print('')
  50.  
  51. for i in computer_data:
  52. #   print(i)                                        #This prints each record to the screen
  53.     name = i[0]                                     #The code only prints the first field
  54.     core = i[1]                                     #The code prints the second field
  55.     speed = i[2]
  56.     ram = i[3]
  57.     cost = i[4]
  58.     print(name,core,speed,ram,cost)
  59.  
  60. print('')
  61. print('Goodbye')
  62.  
  63. chand.close()                                       #This closes the database connector
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement