Python Forum
[Tkinter] TKINTER quiz using sqlite3 database
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] TKINTER quiz using sqlite3 database
#19
here's the working database creation software.
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
Reply


Messages In This Thread
TKINTER quiz using sqlite3 database - by hezza_23 - Apr-01-2019, 01:02 PM
RE: TKINTER quiz using sqlite3 database - by Larz60+ - Apr-05-2019, 03:05 AM
RE: TKINTER quiz using sqlite3 database - by Hilal - Nov-29-2021, 09:42 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  PyQt5 form not displaying my data from SQLite3 Database Linuxdesire 2 5,044 Jan-10-2023, 09:51 PM
Last Post: gradlon93
  Can't get tkinter database aware cascading comboboxes to update properly dford 6 3,749 Jan-11-2022, 08:37 PM
Last Post: deanhystad
Question [Tkinter] data enterred through gui is not storing in sqlite3 database Hilal 21 7,778 Dec-15-2021, 08:48 PM
Last Post: Hilal
  Help with PySimpleGUI INSERT INTO sqlite3 database jrbond 5 7,215 Jul-20-2020, 01:24 PM
Last Post: jrbond
  sQlite3 output to tkinter treeview - how do I set / increase width of the output? dewijones67 5 6,758 Jan-23-2019, 08:45 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020