-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.py
More file actions
63 lines (54 loc) · 1.74 KB
/
Copy pathdb.py
File metadata and controls
63 lines (54 loc) · 1.74 KB
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
import sqlite3
from datetime import datetime
DB_PATH = "search_history.db"
def get_connection():
return sqlite3.connect(DB_PATH)
def create_table_if_not_exists():
conn = get_connection()
c = conn.cursor()
c.execute('''
CREATE TABLE IF NOT EXISTS searches (
id INTEGER PRIMARY KEY AUTOINCREMENT,
answer TEXT,
timestamp TEXT
)
''')
conn.commit()
conn.close()
def add_question_column_if_missing():
conn = get_connection()
c = conn.cursor()
c.execute("PRAGMA table_info(searches)")
columns = [col[1] for col in c.fetchall()]
if "question" not in columns:
try:
c.execute("ALTER TABLE searches ADD COLUMN question TEXT")
print("Added 'question' column to 'searches' table.")
except sqlite3.OperationalError as e:
print("Error adding 'question' column:", e)
conn.commit()
conn.close()
def initialize_db():
create_table_if_not_exists()
add_question_column_if_missing()
def insert_search(question, answer):
conn = get_connection()
c = conn.cursor()
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
c.execute("INSERT INTO searches (question, answer, timestamp) VALUES (?, ?, ?)", (question, answer, timestamp))
conn.commit()
conn.close()
def get_all_searches():
conn = get_connection()
c = conn.cursor()
c.execute("SELECT question, answer, timestamp FROM searches ORDER BY id DESC")
results = c.fetchall()
conn.close()
return results
def clear_history():
conn = get_connection()
c = conn.cursor()
c.execute("DELETE FROM searches")
conn.commit()
conn.close()
initialize_db()