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
#18
first need to create a database. what you supplied was a text file, not a database.
I said I would write (stupid me) a program to create the database from a .csv file.
if a quiz is entered into an excel spread sheet as displayed, and then exported as a .csv file,
the following script will convert into an sqlite3 database with three tables:

There's still one bug to fix:
Error:
Traceback (most recent call last): File ".../Projects/T-Z/T/TryStuff/src/Hezza23/CreateQuestionsDb.py", line 104, in <module> CreateQuestionsDb(dbname='Questions.db', inputfilename='Quiz.csv') File ".../Projects/T-Z/T/TryStuff/src/Hezza23/CreateQuestionsDb.py", line 26, in __init__ self.make_questions_database() File ".../Projects/T-Z/T/TryStuff/src/Hezza23/CreateQuestionsDb.py", line 31, in make_questions_database self.prepair_data() File ".../Projects/T-Z/T/TryStuff/src/Hezza23/CreateQuestionsDb.py", line 41, in prepair_data self.insert_data('Questions', row) File ".../Projects/T-Z/T/TryStuff/src/Hezza23/CreateQuestionsDb.py", line 60, in insert_data self.dbcur.execute(sqlstr) sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 4, and there are 0 supplied.
The query causing the error (in sqlstr) is:
Output:
sqlstr: INSERT INTO Questions VALUES (?, ?, ?, ?), ('1', 'Q', '', 'Which Of these describes an element best?');
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']

        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', row)
                elif row[1] == 'C':
                    self.insert_data('Choices', row)
                elif row[1] == 'A':
                    self.insert_data('self.answer_fields', row)
                else:
                    print(f'row has invalid QuizCode: {row}')

    def insert_data(self, tablename, row):
        sqlstr = None
        qmarks = (f"?, " * len(row))[:-2]
        dbcolumns = '('
        for item in row:
            dbcolumns = f"{dbcolumns}'{item}', "
        dbcolumns = f"{dbcolumns[:-2]})"
        # print(f'\ntablename: {tablename}, qmarks: {qmarks}, dbcolumns: {dbcolumns}')
        sqlstr = f'INSERT INTO {tablename} VALUES ({qmarks}), {dbcolumns};'
        print(f'sqlstr: {sqlstr}')
        # print(f'type: {type(sqlstr)}, self.sqlstr: {sqlstr}')
        self.dbcur.execute(sqlstr)

    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')
Once you have a database, then it can be added to your script.
This is close, perhaps someone will take a look at it while I have my supper, I've seen this error before, but solution escapes me at the moment. I'll be back in a few hours.
getting it into your script should be simple, but can't do it until the database exists.

Database schema looks like this:
Output:
sqlite> .schema CREATE TABLE Questions (QuestionId, QuizCode, unused, Question); CREATE TABLE Choices (QuestionId, QuizCode, SeqLetter, Choice); CREATE TABLE Answers (QuestionId, QuizCode, Answer); sqlite>
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, 01:22 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,037 Jan-10-2023, 09:51 PM
Last Post: gradlon93
  Can't get tkinter database aware cascading comboboxes to update properly dford 6 3,746 Jan-11-2022, 08:37 PM
Last Post: deanhystad
Question [Tkinter] data enterred through gui is not storing in sqlite3 database Hilal 21 7,775 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,750 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