Answer the question
In order to leave comments, you need to log in
When should I create and close cursors when working in SQLite?
Welcome all.
I started to understand the principles of working with the Sqlite database in Python. I read a lot of documentation and examples, but I can not understand such a thing. When do I need to create a database connection, create cursors for SQL queries, and when do I need to close all this?
There is conditionally such a code (Bot in Telegram):
connection = sqlite3.connect('users_db.sqlite', check_same_thread=False)
bot = telebot.TeleBot('bla-bla')
def create_database():
cursor = connection.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS users(
t_id TEXT PRIMARY KEY NOT NULL,
username TEXT,
first_name TEXT,
last_name TEXT,
_group TEXT) WITHOUT ROWID""")
connection.commit()
cursor.close()
def get_user_group(user_id):
cursor = connection.cursor()
cursor.execute("""SELECT _group FROM users WHERE t_id=?""", (user_id,))
connection.commit()
user_group = cursor.fetchone()
cursor.close()
if not user_group:
return False
return user_group[0]
def add_or_update_user_to_db(chat, group):
if not get_user_group(chat.id):
cursor = connection.cursor()
cursor.execute("""INSERT INTO users (t_id, username, first_name, last_name, _group) VALUES (?, ?, ?, ?, ?)""",
(chat.id, chat.username, chat.first_name, chat.last_name, group))
connection.commit()
cursor.close()
else:
cursor = connection.cursor()
cursor.execute("""UPDATE users SET _group=? WHERE t_id=?""", (group, chat.id))
connection.commit()
cursor.close()
@bot.message_handler(content_types=["text"])
def main_menu(message):
# тут условно обработка сообщений
if __name__ == '__main__':
create_database()
bot.polling(none_stop=True, interval=2) # бесконечный цикл
Answer the question
In order to leave comments, you need to log in
It is better to close cursors immediately as they are no longer needed and, as far as I remember, you can work with them in the with construction (there is automatic closure).
Something like
with connection.cursor() as cursor:
do_something_with(cursor)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question