Пытался подключить к боту базу данных sqlite базу создал а как подключить что бы все сохранялось не знаю
Вот код (это эхо бот) там снизу функция lalala отправляет сообщение как сделать что бы она подключилась к базе и сохраняла туда сообщения
import telebot
import config
import sqlite3
bot = telebot.TeleBot(config.TOKEN)
__connection = None
def get_connection():
global __connection
if __connection is None:
__connection = sqlite3.connect('anketa.db')
return __connection
def init_db(force: bool = False):
conn = get_connection()
c = conn.cursor()
if force:
c.execute('DROP TABLE IF EXISTS user_message')
c.execute('''
CREATE TABLE IF NOT EXISTS user_message (
id INTEGER PRIMARY KEY,
user_id INTEGER NOT NULL,
text TEXT NOT NULL
)
''')
conn.commit()
def add_message(user_id: int, text: str):
conn = get_connection()
c = conn.cursor()
c.execute('INSERT INTO user_message (user_id, text) VALUES (?, ?)', (user_id, text))
conn.commit()
@bot.message_handler(content_types=['text'])
def lalala(message):
bot.send_message(message.chat.id, message.text)
add_message((message.from_user.first_name, message.from_user.last_name, str(message.from_user.id), message.text))
bot.polling(none_stop=True)
Ответы (1 шт):
Автор решения: Andrew
→ Ссылка
Создание базы данных
import sqlite3
conn = sqlite3.connect("mydatabase.db") # или :memory: чтобы сохранить в RAM
cursor = conn.cursor()
# Создание таблицы
cursor.execute("""CREATE TABLE albums
(title text, artist text, release_date text,
publisher text, media_type text)
""")
# Вставляем данные в таблицу
cursor.execute("""INSERT INTO albums
VALUES ('Glow', 'Andy Hunter', '7/24/2012',
'Xplore Records', 'MP3')"""
)
# Сохраняем изменения
conn.commit()
# Вставляем множество данных в таблицу используя безопасный метод "?"
albums = [('Exodus', 'Andy Hunter', '7/9/2002', 'Sparrow Records', 'CD'),
('Until We Have Faces', 'Red', '2/1/2011', 'Essential Records', 'CD'),
('The End is Where We Begin', 'Thousand Foot Krutch', '4/17/2012', 'TFKmusic', 'CD'),
('The Good Life', 'Trip Lee', '4/10/2012', 'Reach Records', 'CD')]
cursor.executemany("INSERT INTO albums VALUES (?,?,?,?,?)", albums)
conn.commit()
Редактирование/удаление
import sqlite3
conn = sqlite3.connect("mydatabase.db")
cursor = conn.cursor()
sql = """
UPDATE albums
SET artist = 'John Doe'
WHERE artist = 'Andy Hunter'
"""
cursor.execute(sql)
conn.commit()
Основные запросы :
import sqlite3
conn = sqlite3.connect("mydatabase.db")
#conn.row_factory = sqlite3.Row
cursor = conn.cursor()
sql = "SELECT * FROM albums WHERE artist=?"
cursor.execute(sql, [("Red")])
print(cursor.fetchall()) # or use fetchone()
print("Here's a listing of all the records in the table:")
for row in cursor.execute("SELECT rowid, * FROM albums ORDER BY artist"):
print(row)
print("Results from a LIKE query:")
sql = "SELECT * FROM albums WHERE title LIKE 'The%'"
cursor.execute(sql)
print(cursor.fetchall())
Источник https://python-scripts.com/sqlite