· 2 years ago · Sep 14, 2023, 07:50 PM
1import sqlite3
2
3
4class Database:
5 def __init__(self, db_file):
6 self.conn = sqlite3.connect(db_file)
7 self.cursor = self.conn.cursor()
8
9 CREATE_TABLE_COMMAND = """CREATE TABLE IF NOT EXISTS users (id BIGINT PRIMARY KEY, user_id INT, user_name TEXT, money INT)"""
10 self.cursor.execute(CREATE_TABLE_COMMAND)
11
12 def user_exists(self, user_id):
13 self.cursor.execute("SELECT 1 FROM users WHERE user_id=?", (user_id,))
14 return None if self.cursor.fetchone() is None else True
15
16 def add_user(self, user_id, user_name):
17 if not self.user_exists(user_id):
18 with self.conn:
19 self.cursor.execute("INSERT INTO 'users' ('user_id', 'user_name') VALUES (?,?)", (user_id, user_name,))
20 self.conn.commit()
21 else:
22 print('user already exists')
23
24 def set_user_money(self, user_id, money):
25 self.cursor.execute("UPDATE users SET money=? WHERE user_id=?", (money, user_id,))
26 self.conn.commit()
27
28 def get_user_money(self, user_id):
29 self.cursor.execute("SELECT money FROM users WHERE user_id=?", (user_id,))
30 return self.cursor.fetchone()[0]
31
32
33
34