V
V
Vova Efanov2021-05-10 22:26:51
Python
Vova Efanov, 2021-05-10 22:26:51

Data output from the database to your telegram bot python profile?

class SQLighter:
  def __init__(self, database):
      self.connection = sqlite3.connect(database, check_same_thread = False)
      self.cursor = self.connection.cursor()
      self.cursor.execute("CREATE TABLE IF NOT EXISTS stats (user_id INT, user_name TEXT, survived INT, infected INT)")
  def add_user(self, id, name, survived, infected):
      #"""Добавляем значение"""
      with self.connection:
          return self.cursor.execute("""INSERT INTO `stats` (user_id, user_name, survived, infected) VALUES (?,?,?,?)""", (id, name, survived, infected))
  def get_nick(self, id):
      #'''Эта функция позволяет извлекать нужное значение(в данном случае id) из таблицы stats'''
      with self.connection:
          return self.cursor.execute("SELECT user_id FROM stats WHERE id = ?", (id,)).fetchall()
  def set_fast(self, id):
      #'''Эта функция позволяет устанавливать значение исходя из параметра id'''
      with self.connection:
          return self.cursor.execute("UPDATE stats SET infected=X WHERE id=?", (id))
  

sql_lighter = SQLighter("database.db")
sql_lighter.add_user(982543922, "Владимир", 1, 1)

Мой профиль:

bot.send_message(message.chat.id, f"Мой профиль\nМой ID: [{message.from_user.id}]\nМой Псевдоним: [{message.from_user.username}]\nМоё Ф.И: [{message.from_user.first_name} {message.from_user.last_name}]\nКоличество побед за выжившего: [{survived}]\nКоличество заражений за заражённого: [{infected}]")

How can I extract data from the database to my telegram bot profile?
Profile - my statistics

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
o5a, 2021-05-11
@o5a

If it is more convenient, then you can get data in the form of a dictionary (where the keys are the names of the columns). Then you can directly access the desired field by name.

class SQLighter:
  def __init__(self, database):
      self.connection = sqlite3.connect(database, check_same_thread = False)
      self.connection.row_factory = sqlite3.Row # этой строкой указываем, что результат получаем в виде словаря
      self.cursor = self.connection.cursor()
      self.cursor.execute("CREATE TABLE IF NOT EXISTS stats (user_id INT, user_name TEXT, survived INT, infected INT)")
...
  # и можно сделать такую функцию, возвращающую всю информацию пользователя
  def get_info(self, id):
      with self.connection:
          return self.cursor.execute("SELECT * FROM stats WHERE user_id=?", (id, )).fetchone()

sql_lighter = SQLighter("database.db")
sql_lighter.add_user(982543922, "Владимир", 1, 1)
# затем получаем весь словарь данных и можем использовать любые нужные поля из него
data = sql_lighter.get_info(982543922)
print(data)
print(data['user_name'])
print("Информация пользователя {}: имя: {}, survived: {}, infected: {}".format(data['user_id'], data['user_name'], data['survived'], data['infected']))

T
tshipenchko, 2021-05-12
@tshipenchko

Just by the way, why did you not like ORM)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question