scientific-programming-exer.../exam/ex3/database.py

68 lines
1.7 KiB
Python
Raw Normal View History

2019-01-31 16:51:05 +00:00
import os
import sqlite3
import random
from cfg import config
database_path = os.path.join(config["APP_PATH"], "app.sqlite")
def create_database():
# truncate the file if it exists
with open(database_path, "w") as database_file:
pass
db = sqlite3.connect(database_path)
db.execute('''CREATE TABLE QUESTIONS(question TEXT, answer TEXT, correct INT)''')
db.close()
def open_database():
if(not os.path.exists(database_path)):
create_database()
return sqlite3.connect(database_path)
def update_correct(question, correct):
"""
Correct has to be +1 (for a correct answer) or -1 (for a wrong answer).
"""
db = open_database()
cursor = db.cursor()
cursor.execute("UPDATE QUESTIONS SET correct=correct + ? WHERE question = ?", (correct, question))
db.close()
def add_word(question, answer):
db = open_database()
cursor = db.cursor()
cursor.execute("INSERT INTO QUESTIONS(question, answer, correct) VALUES(?, ?, 0)", (question, answer))
db.close()
def add_words(input_data):
db = open_database()
cursor = db.cursor()
cursor.executemany("INSERT INTO QUESTIONS(question, answer, correct) VALUES(?, ?, 0)", input_data.items())
db.close()
print("added words")
def fetch_question():
db = open_database()
cursor = db.cursor()
cursor.execute("SELECT COUNT(question) FROM questions")
number_of_questions = cursor.fetchone()[0]
if(number_of_questions == 0):
raise Exception("No questions in the database")
fetch_questions = number_of_questions // config["WORD_BUCKET_SIZE"]
if(fetch_questions == 0):
fetch_questions = 1
cursor.execute("SELECT question, answer, correct FROM QUESTIONS SORT BY correct")
result = cursor.fetch(fetch_questions)
my_result = random.choice(result)
return result[:2]