Apr-05-2019, 03:05 AM
here's the working database creation software.
Will take a look at reading it into your GUI on my AM around 10:00 EST
import sqlite3 from pathlib import Path import os import csv import sys class CreateQuestionsDb: def __init__(self, dbname, inputfilename): # create directory anchor os.chdir(os.path.abspath(os.path.dirname(__file__))) homepath = Path('.') datadir = homepath / 'QuestionsDatabase' datadir.mkdir(exist_ok = True) self.database = datadir / dbname self.datafile = datadir / inputfilename self.sqlstr = None self.dbcon = None self.dbcur = None self.question_fields = ['QuestionId', 'QuizCode', 'Unused', 'Question'] self.choice_fields = ['QuestionId', 'QuizCode', 'SeqLetter', 'Choice'] self.answer_fields = ['QuestionId', 'QuizCode', 'Answer', 'Unused'] self.make_questions_database() def make_questions_database(self): self.db_connect() self.create_tables() self.prepair_data() self.db_close() def prepair_data(self): with self.datafile.open() as fp: crdr = csv.reader(fp, delimiter=',') next(crdr) for row in crdr: # print(f'row[1]: {row[1]}') if row[1] == 'Q': self.insert_data('Questions', self.question_fields, row) elif row[1] == 'C': self.insert_data('Choices', self.choice_fields, row) elif row[1] == 'A': self.insert_data('Answers', self.answer_fields, row) else: print(f'row has invalid QuizCode: {row}') def insert_data(self, tablename, fields, row): sqlstr = None qmarks = (f"?, " * len(row))[:-2] dbcolumns = '(' for item in row: dbcolumns = f"{dbcolumns}'{item}', " dbcolumns = f"{dbcolumns[:-2]})" xfields = ', '.join(fields) sqlstr = f''' INSERT INTO {tablename} ({(xfields)}) VALUES ({qmarks}) ''' cur = self.dbcon.cursor() cur.execute(sqlstr, row) def db_connect(self): try: self.dbcon = sqlite3.connect(self.database) self.dbcur = self.dbcon.cursor() except sqlite3.Error as e: print(e) def drop_table(self, tablename): self.sqlstr = f'DROP TABLE IF EXISTS {tablename};' def add_table(self, tablename, column_list): columns = ', '.join(column_list) self.sqlstr = f'CREATE TABLE IF NOT EXISTS {tablename} ({columns});' self.dbcur.execute(self.sqlstr) def create_tables(self): tablename = 'Questions' self.drop_table(tablename) self.add_table(tablename, self.question_fields) tablename = 'Choices' self.drop_table(tablename) self.add_table(tablename, self.choice_fields) tablename = 'Answers' self.drop_table(tablename) self.add_table(tablename, self.answer_fields) self.db_commit() def db_close(self, rollback=False): if rollback: self.dbcon.rollback() else: self.dbcon.commit() self.dbcon.close() def db_commit(self): self.dbcon.commit() if __name__ == '__main__': CreateQuestionsDb(dbname='Questions.db', inputfilename='Quiz.csv')run it using Quiz.csv which was an attachment on previous post, and it will create the database in a directory named 'QuestionsDatabase' immediately below script directory.
Will take a look at reading it into your GUI on my AM around 10:00 EST