External Exam Download Resources Web Applications Games Recycle Bin

CREATE UPDATE DELETE using a new logins table

createupdatedelete1.py

import sqlite3

userLogins = [
  ("hide@secret.com","abcd1234"),
  ("fake@hidden.com","shhhhhhh"),
  ("loud@public.com","password")
]

try:
  db = sqlite3.connect('accounts.db')
  cursor = db.cursor()
  cursor.execute("CREATE TABLE logins(email TEXT PRIMARY KEY, password TEXT);")
  cursor.executemany('''INSERT INTO logins (email, password)
                          VALUES (?, ?)''', userLogins)

  #commit both changes at once:
  db.commit()
  print("Database created AND records inserted successfully.")

except Exception as error:
  db.rollback()
  print("Something went wrong: " + str(error))

finally:
  db.close()

createupdatedelete2.py

#before running this, make sure you have run createupdatedelete1.py ^^

import sqlite3

#UPDATE table
#SET column_1 = new_value_1,
#    column_2 = new_value_2
#WHERE
#    search_condition 

updateStatement = """
  UPDATE logins
    SET password = ?
  WHERE
    email == ?
"""

selectStatement = """
  SELECT * FROM logins
"""

try:
  db = sqlite3.connect('accounts.db')
  cursor = db.cursor()
  cursor.execute(selectStatement)
  result = cursor.fetchall()
  for each_record in result:
    print(each_record, end='\n')

  email = input("Enter your email: ")
  password = input("Enter your new password: ")

  cursor.execute(updateStatement, (password, email)) #be careful of ordering
  db.commit()
  print("Update complete. View changes in DB Browser for SQLite.")

except Exception as error:
  db.rollback()
  print("Something went wrong: " + str(error))

finally:
  db.close()

createupdatedelete3.py

#before running this, make sure you have run createupdatedelete1.py ^^

import sqlite3

#DELETE
#FROM table
#WHERE search_condition

deleteStatement = """
  DELETE 
    FROM logins
  WHERE
    email == ?
"""

selectStatement = """
  SELECT * FROM logins
"""

try:
  db = sqlite3.connect('accounts.db')
  cursor = db.cursor()
  cursor.execute(selectStatement)
  result = cursor.fetchall()
  for each_record in result:
    print(each_record, end='\n')

  email = input("Enter email of account to delete: ")
  cursor.execute(deleteStatement, (email,))
  db.commit()
  print("Delete complete. View changes in DB Browser for SQLite.")

except Exception as error:
  db.rollback()
  print("Something went wrong: " + str(error))

finally:
  db.close()