Suggest a feature
×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Python
Posted by: Peter Tsiampas
Added: Apr 15, 2018 12:21 PM
Views: 16
  1. import sqlite3
  2.  
  3. # Attach to (or create) the database
  4. connection = sqlite3.connect("c:\studentRecords.db")
  5.  
  6. # Create a new table with three fields
  7. cursor = connection.cursor()
  8. cursor.execute("""CREATE TABLE StudentSubjects
  9.                 (studentName text, year integer, subject text)""")
  10.  
  11. print("Database table StudentSubjects has been created.")
  12.  
  13. # Create some testdata, and write rows to the table.
  14. test_data = [
  15.     ("John",  2012, ["CompSci", "Physics"]),
  16.     ("Vusi",  2012, ["Maths", "CompSci", "Stats"]),
  17.     ("Jess",  2011, ["CompSci", "Accounting", "Economics", "Management"]),
  18.     ("Sarah", 2011, ["InfSys", "Accounting", "Economics", "CommLaw"]),
  19.     ("Zuki",  2012, ["Sociology", "Economics", "Law", "Stats", "Music"])]
  20.  
  21. for (student, yr, subjects) in test_data:
  22.     for subj in subjects:
  23.         t = (student, yr, subj)
  24.         cursor.execute("INSERT INTO StudentSubjects VALUES (?,?,?)", t)
  25.  
  26. connection.commit()
  27.  
  28. # Now verify that we did write the data
  29. cursor.execute("SELECT COUNT(*) FROM StudentSubjects")
  30. result = cursor.fetchall()
  31. numrecs = result[0][0]
  32. cursor.close()
  33.  
  34. print("StudentSubjects table now has {0} rows of data.".format(numrecs))