Neduri/problem-solve-hub
0
1import sqlite3
2
3# Create a new SQLite database (or connect to an existing one)
4def create_db():
5 conn = sqlite3.connect('solutions.db') # Creates a file named 'solutions.db'
6 cursor = conn.cursor()
7
8 # Create table for users if it doesn't exist
9 cursor.execute('''
10 CREATE TABLE IF NOT EXISTS users (
11 id INTEGER PRIMARY KEY AUTOINCREMENT,
12 username TEXT UNIQUE NOT NULL,
13 password TEXT NOT NULL
14 )
15 ''')
16
17 # Create table for storing solutions
18 cursor.execute('''
19 CREATE TABLE IF NOT EXISTS solutions (
20 id INTEGER PRIMARY KEY AUTOINCREMENT,
21 category TEXT NOT NULL,
22 problem TEXT NOT NULL,
23 solution TEXT NOT NULL
24 )
25 ''')
26
27 conn.commit()
28 conn.close()
29
30# Function to add a new user to the users table
31def add_user(username, password):
32 conn = sqlite3.connect('solutions.db')
33 cursor = conn.cursor()
34 cursor.execute('''
35 INSERT INTO users (username, password)
36 VALUES (?, ?)
37 ''', (username, password))
38 conn.commit()
39 conn.close()
40
41# Function to check user login credentials
42def login_user(username, password):
43 conn = sqlite3.connect('solutions.db')
44 cursor = conn.cursor()
45 cursor.execute('''
46 SELECT * FROM users WHERE username = ? AND password = ?
47 ''', (username, password))
48 user = cursor.fetchone() # Fetch the first user match
49 conn.close()
50 return user # If user exists, returns user data, else None
51
52# Function to add a solution to the database
53def add_solution(category, problem, solution):
54 conn = sqlite3.connect('solutions.db')
55 cursor = conn.cursor()
56 cursor.execute('''
57 INSERT INTO solutions (category, problem, solution)
58 VALUES (?, ?, ?)
59 ''', (category, problem, solution))
60 conn.commit()
61 conn.close()
62
63# Function to get solutions from the database based on category and problem
64def get_solutions_from_db(category, problem):
65 conn = sqlite3.connect('solutions.db')
66 cursor = conn.cursor()
67 cursor.execute('''
68 SELECT solution FROM solutions WHERE category = ? AND problem LIKE ?
69 ''', (category, f"%{problem}%"))
70 solutions = cursor.fetchall()
71 conn.close()
72 return [solution[0] for solution in solutions] # Returns list of solutions
73
74# Create the database and tables if they don't exist
75create_db()
76 