File size: 1,898 Bytes
e60c070
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import sqlite3
from loguru import logger

DB_PATH = './database/word_database.db'

class WordsDB(object):
    def __init__(self):
        logger.info('Initialized words database.')
    
    def _connect_db(self):
        conn = sqlite3.connect(
            DB_PATH,
            timeout=10, 
            check_same_thread=False)
        cursor = conn.cursor()
        cursor.execute('''
        CREATE TABLE IF NOT EXISTS words (
            id INTEGER PRIMARY KEY,
            word TEXT NOT NULL,
            definition TEXT NOT NULL
        )
        ''')
        return conn, conn.cursor()


    def add_word(self, word, definition):
        self.conn, self.cursor = self._connect_db()
        self.cursor.execute('INSERT INTO words (word, definition) VALUES (?, ?)', (word, definition))
        self.conn.commit()
        self.cursor.close()
        self.conn.close()
        

    def delete_word(self, word):
        self.conn, self.cursor = self._connect_db()
        self.cursor.execute('DELETE FROM words WHERE word = ?', (word,))
        self.conn.commit()
        self.cursor.close()
        self.conn.close()

    def update_word(self, word, new_definition):
        self.conn, self.cursor = self._connect_db()
        self.cursor.execute('UPDATE words SET definition = ? WHERE word = ?', (new_definition, word))
        self.conn.commit()
        self.cursor.close()
        self.conn.close()

    def query_word(self):
        self.conn, self.cursor = self._connect_db()
        self.cursor.execute('SELECT * FROM words')
        res = self.cursor.fetchall()
        self.cursor.close()
        self.conn.close()
        return res
    

words_db = WordsDB()

if __name__ == '__main__':

    words_db.add_word('apple', '苹果')
    words_db.add_word('banana', '香蕉')
    words_db.update_word('banana', '新的香蕉')
    result = words_db.query_word('banana')
    print(result)